我想要做这样的事情:有没有办法可以动态地将属性添加到python方法?
class Foo:
def test(self, arg):
self.test.x = 'prop x with ' + arg
print "test!"
f = Foo()
f.test('bar')
print f.test.x
并获得尽可能的输出是这样的:
test!
prop x with bar
而是我得到一个AttributeError: 'instancemethod' object has no attribute 'x'
顺便说一句,我可以用功能做这样的事情:
def test(arg):
test.x = 'prop x ' + arg
print "test!"
test('bar')
print test.x
其中工作得很好。
不知道你为什么想这样做。为什么不直接向实例添加属性,而不是方法? –
我从方法动态调用另一个方法,我想将一些信息保存到一个函数的属性,但我不想使用其他类,只是为了保持简单。 – Helvdan