2016-02-29 114 views
3

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

其中工作得很好。

+3

不知道你爲什麼想這樣做。爲什麼不直接向實例添加屬性,而不是方法? –

+0

我從方法動態調用另一個方法,我想將一些信息保存到一個函數的屬性,但我不想使用其他類,只是爲了保持簡單。 – Helvdan

回答

2

你不能做到這一點;即使可以,方法也是類的屬性,而不是實例,所以對於Foo的所有實例都會設置相同的值。

相反,你應該簡單地直接分配到該實例。你可以添加你喜歡的任何屬性。

class Foo: 
    def test(self, arg): 
     self._x = 'prop x with ' + arg 
2

即使成功設置了屬性,也不會保留。在CPython的,是動態創建綁定方法在您訪問:

>>> class Foo: 
... def test(self, arg): pass 
... 
>>> f = Foo() 
>>> f.test is f.test 
False 
1

您可以添加成員一個類的實例,而不是一個方法。

class Foo: 
    def test(self, arg): 
    self.x = 'prop x with ' + arg 
    print "test!" 

f = Foo() 
f.test('bar') 
print f.x 
1

我們可以到/達到你是痘痘調整

from collections import namedtuple 

T = namedtuple('T', ['x']) 

class Foo: 
    def test(self, arg): 
     self.test = T('prop x with ' + arg) 
     print "test!" 

f = Foo() 
f.test('bar') 
print f.test.x 

輸出會找什麼:

test! 
prop x with bar 

原因我把它叫做一個調整是從這一點來說,f.test不再是可調用的。

+2

但是然後'f.test'不再可以被調用 –

+0

這就是我稱之爲調整的原因:) 讓我補充一點,作爲我的答案的註釋,一旦我們這樣做,f.test不再是可調用的 –

+0

好的,謝謝,但我仍然需要調用這個方法。 – Helvdan

相關問題