我想要一个像object.x
这样的属性调用返回某种方法的结果,比如object.other.other_method()
。我怎样才能做到这一点?Python:如何使对象属性参考调用方法
编辑:我很快就问了一下:它看起来像我能做到这一点与
object.__dict__['x']=object.other.other_method()
这是做到这一点的方式OK?
我想要一个像object.x
这样的属性调用返回某种方法的结果,比如object.other.other_method()
。我怎样才能做到这一点?Python:如何使对象属性参考调用方法
编辑:我很快就问了一下:它看起来像我能做到这一点与
object.__dict__['x']=object.other.other_method()
这是做到这一点的方式OK?
使用属性装饰
class Test(object): # make sure you inherit from object
@property
def x(self):
return 4
p = Test()
p.x # returns 4
与__dict__碴脏了,尤其是当@property可用。
有没有办法做到这一点动态? – zml 2017-08-11 11:25:30
看看内置的property函数。
使用property
http://docs.python.org/library/functions.html#property
class MyClass(object):
def __init__(self, x):
self._x = x
def get_x(self):
print "in get_x: do something here"
return self._x
def set_x(self, x):
print "in set_x: do something"
self._x = x
x = property(get_x, set_x)
if __name__ == '__main__':
m = MyClass(10)
# getting x
print 'm.x is %s' % m.x
# setting x
m.x = 5
# getting new x
print 'm.x is %s' % m.x
创建
object.__dict__['x']=object.other.other_method()
相反,你可以做到这一点
object.x = property(object.other.other_method)
当这只会叫
other_method
一次
每次调用other_method
object.x
访问
当然,你并没有真正使用object
作为变量名,对吗?
Re:你的编辑 - 是和不是......你的解决方案将* object.other.other_method()的结果存储在object.x中,这意味着该方法只会被调用一次,而不是每次调用读取时间'object.x'。如果你想每次都调用这个方法,@ muksie说得对 - 请查看'property'装饰器。 – 2010-07-02 14:57:33