exec to add a function into a class
So I've looked at similar questions, and I've found some solutions to this, but I can't quite figure out how to do this. What I'm trying to do is add a method to a class from a string. I can do this with the setattr() method, but that won't let me use self as an attribute in the extra method. Here's an example: (and I apologize for the variable names, I always use yolo when I'm mocking up an idea) class what: def __init__(self): s = 'def yolo(self):\n\tself.extra = "Hello"\n\tprint self.extra' exec(s) setattr(self,"yolo",yolo) what().yolo() returns this: Traceback (most recent call last): File