有没有一种方法可以动态地向python方法添加属性?
我想这样做:有没有一种方法可以动态地向python方法添加属性?,python,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 并得到如下输出: class Foo: def test(self, arg): self.test.x = 'prop x wit
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
并得到如下输出:
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'对象没有属性“x”
顺便说一句,我可以用函数做这样的事情:
def test(arg):
test.x = 'prop x ' + arg
print "test!"
test('bar')
print test.x
这很好用。你不能这样做;即使可以,方法也是类的属性,而不是实例的属性,因此将为Foo的所有实例设置相同的值 相反,您应该直接分配给实例。您可以添加任何您喜欢的属性
class Foo:
def test(self, arg):
self._x = 'prop x with ' + arg
即使您成功地设置了属性,它也不会被保留。在CPython中,绑定方法是在访问它们时动态创建的:
>>> class Foo:
... def test(self, arg): pass
...
>>> f = Foo()
>>> f.test is f.test
False
可以将成员添加到类实例,但不能添加到方法
class Foo:
def test(self, arg):
self.x = 'prop x with ' + arg
print "test!"
f = Foo()
f.test('bar')
print f.x
通过微调,我们可以达到/实现您所期望的目标
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不再是可调用的。不确定为什么要这样做。为什么不直接向实例添加一个属性,而不是方法?我正在从方法中动态调用另一个方法,我想将一些信息保存到函数的属性中,但我不想使用其他类,只是为了让事情简单些。但是,
f.test
不再是可调用的,这就是我称之为调整的原因:)让我在我的回答中补充一下,一旦我们这样做,f.test就不再是可调用的了