2010-07-02 41 views
16

我想要一个像object.x这样的属性调用返回某种方法的结果,比如object.other.other_method()。我怎样才能做到这一点?Python:如何使对象属性参考调用方法

编辑:我很快就问了一下:它看起来像我能做到这一点与

object.__dict__['x']=object.other.other_method() 

这是做到这一点的方式OK?

+2

Re:你的编辑 - 是和不是......你的解决方案将* object.other.other_method()的结果存储在object.x中,这意味着该方法只会被调用一次,而不是每次调用读取时间'object.x'。如果你想每次都调用这个方法,@ muksie说得对 - 请查看'property'装饰器。 – 2010-07-02 14:57:33

回答

28

使用属性装饰

class Test(object): # make sure you inherit from object 
    @property 
    def x(self): 
     return 4 

p = Test() 
p.x # returns 4 

与__dict__碴脏了,尤其是当@property可用。

+0

有没有办法做到这一点动态? – zml 2017-08-11 11:25:30

4

使用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 
2

创建

object.__dict__['x']=object.other.other_method() 

相反,你可以做到这一点

object.x = property(object.other.other_method) 
当这只会叫 other_method一次

每次调用other_methodobject.x访问

当然,你并没有真正使用object作为变量名,对吗?

+0

嘿,不,我不是:)。感谢您的回答,请点赞! – mellort 2010-07-02 18:56:11

+0

当使用这个选项'object.x = property(object.other.other_method)'时,我在访问'x'属性时获得'',我该怎么做不同? – zml 2017-08-11 11:06:02

相关问题