我希望像object.x
这样的属性调用返回某些方法的结果,比如object.other.other_method()
。我怎么能这样做?
编辑:我很快就问了一下:看起来我可以用
做到这一点object.__dict__['x']=object.other.other_method()
这是一种可行的方法吗?
答案 0 :(得分:35)
使用属性装饰器
class Test(object): # make sure you inherit from object
@property
def x(self):
return 4
p = Test()
p.x # returns 4
使用__dict__进行捣乱很脏,特别是在@property可用时。
答案 1 :(得分:11)
查看内置的property函数。
答案 2 :(得分:5)
使用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
答案 3 :(得分:3)
这只会在创建时调用other_method
object.__dict__['x']=object.other.other_method()
相反,你可以这样做
object.x = property(object.other.other_method)
每次访问other_method
时都会调用object.x
当然你并没有真正使用object
作为变量名,是吗?