从 python 中动态添加的方法访问对象成员
access object members from dynamically added methods in python
我在使用动态生成的方法共享 class 的成员时遇到问题。
例如,从 __init__
和 normal_test
访问的 x
与从动态绑定方法 test
和 [=17= 访问的 x
不同]:
class Foo:
def __init__(self):
self.x = 10
def normal_test(self):
print self.x
def bar(self):
print self.x
def setx_method(self,x):
self.x = x
setattr(Foo, "test", classmethod(bar))
setattr(Foo, "setx", classmethod(setx_method))
f = Foo();
f.setx(5)
f.test()
f.normal_test()
我应该如何编写代码以使 self.x
引用相同的 x
?
你不应该将 @classmethod
与 self
一起使用,因为它指向你的 class 实例,而在 @classmethod
中你应该使用 cls
作为它指向整个 class。
看这里:Meaning of @classmethod and @staticmethod for beginner?
所以最简单的解决方案就是删除 classmethod
:
setattr(Foo, "test", bar)
setattr(Foo, "setx", setx_method)
正在分析
setattr(Foo, "setx", classmethod(setx_method))
相当于
@classmethod
def setx_method(self,x):
self.x=x
现在,当您调用 f.setx(5)
时,它实际上将 f
的 class(ie, Foo)
与 self 绑定,将 5 与 x
绑定,因此它执行了 Foo.x = 5
简而言之,您在 Foo
中有两个 x
,一个是实例成员 x
,一个是 class 成员 x
。
f.setx(5) # sets class x
f.test() # print class variable x
f.normal_test() # print instance variable x
我在使用动态生成的方法共享 class 的成员时遇到问题。
例如,从 __init__
和 normal_test
访问的 x
与从动态绑定方法 test
和 [=17= 访问的 x
不同]:
class Foo:
def __init__(self):
self.x = 10
def normal_test(self):
print self.x
def bar(self):
print self.x
def setx_method(self,x):
self.x = x
setattr(Foo, "test", classmethod(bar))
setattr(Foo, "setx", classmethod(setx_method))
f = Foo();
f.setx(5)
f.test()
f.normal_test()
我应该如何编写代码以使 self.x
引用相同的 x
?
你不应该将 @classmethod
与 self
一起使用,因为它指向你的 class 实例,而在 @classmethod
中你应该使用 cls
作为它指向整个 class。
看这里:Meaning of @classmethod and @staticmethod for beginner?
所以最简单的解决方案就是删除 classmethod
:
setattr(Foo, "test", bar)
setattr(Foo, "setx", setx_method)
正在分析
setattr(Foo, "setx", classmethod(setx_method))
相当于
@classmethod
def setx_method(self,x):
self.x=x
现在,当您调用 f.setx(5)
时,它实际上将 f
的 class(ie, Foo)
与 self 绑定,将 5 与 x
绑定,因此它执行了 Foo.x = 5
简而言之,您在 Foo
中有两个 x
,一个是实例成员 x
,一个是 class 成员 x
。
f.setx(5) # sets class x
f.test() # print class variable x
f.normal_test() # print instance variable x