2010-07-02 98 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