2016-02-29 112 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

相关问题