在运行时确定的名称/值,将方法/状态动态添加到类/实例中



我需要动态添加一个在运行时确定的名称的类方法,也需要在运行时确定的内部状态。这是我可以做饭的最简单示例:

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((返回语句似乎与h((中的原始定义绑定,而不是其在foo中的新上下文。我尝试了许多事情,并查看了堆栈溢出中的内省和其他主题,但空无一人。如何修改此代码,以使最后一行产生"某物"?

您在h内部混淆了 local变量 state,这与函数对象上的属性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'

最新更新