我想要做這樣的事情:有沒有辦法可以動態地將屬性添加到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