exec将函数添加到类中 [英] 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.
我想做的是从字符串向类添加方法.我可以使用setattr()
方法来执行此操作,但这不会让我在其他方法中将self
用作属性.这是一个示例:(我为变量名表示歉意,在构思一个想法时总是使用yolo)
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()
返回此:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: yolo() takes exactly 1 argument (0 given)
,如果s = 'def yolo():\n\tself.extra = "Hello"\n\tprint self.extra'
然后我得到这个结果:
and if s = 'def yolo():\n\tself.extra = "Hello"\n\tprint self.extra'
then I get this result:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 2, in yolo
NameError: global name 'self' is not defined
从本质上讲,这意味着我无法为类动态创建方法,我知道这是一种不好的做法,而且是非Python的,因为这些方法将无法访问该类其余部分可以访问的变量.
This essentially means that I cannot dynamically create methods for classes, which I know is bad practice and unpythonic, because the methods would be unable to access the variables that the rest of the class has access to.
感谢您的帮助.
推荐答案
您必须将函数绑定到类实例,才能将其转换为方法.可以将其包装在 types.MethodType
中:
You have to bind your function to the class instance to turn it into a method. It can be done by wrapping it in types.MethodType
:
import types
class what:
def __init__(self):
s = 'def yolo(self):\n\tself.extra = "Hello"\n\tprint self.extra'
exec(s)
self.yolo = types.MethodType(yolo, self)
what().yolo()
在旁注中,为什么在这种情况下您甚至需要exec
?你也可以写
On a side note, why do you even need exec
in this case? You can just as well write
import types
class what:
def __init__(self):
def yolo(self):
self.extra = "Hello"
print self.extra
self.yolo = types.MethodType(yolo, self)
what().yolo()
for the sake of completeness, one might prefer a solution through the descriptor protocol:
class what:
def __init__(self):
def yolo(self):
self.extra = "Hello"
print self.extra
self.yolo = yolo.__get__(self)
what().yolo()
这篇关于exec将函数添加到类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!