我需要动态添加一个类方法,该方法具有在运行时确定的名称,以及在运行时确定的内部状态。这是我可以做的最简单的例子:
class foo():
pass
def h(self): # h() is just a placeholder until we can do setattr()
state = 'none'
return state
setattr(h,'state','something')
setattr(foo,'bar',h)
del(h)
print(dir(foo)) # includes 'bar'
print(dir(foo.bar)) # includes 'state'
print(getattr(foo.bar,'state')) # 'something'
f = foo()
print(getattr(f.bar,'state')) # 'something'
# all is well up to here, but now we go awry
print(f.bar()) # 'none'
在最后一行中,bar()return语句似乎绑定到h()中的原始定义,而不是foo中的新上下文。我尝试了很多东西,并在堆栈溢出中查看了内省和其他主题,但是空洞了。如何修改此代码,以便最后一行产生'某事'?
你在state
中混淆局部变量h
,它与函数对象h.state
上的属性无关。他们没有关系......注意,f.bar.state
会给你'something'
。
你可以这样做:
In [6]: class Foo: pass
In [7]: def h(self):
...: return self.state
...:
In [8]: Foo.bar = h
In [9]: f = Foo()
In [10]: f.state = 'something'
In [11]: f.bar()
Out[11]: 'something'