Python: How to make object attribute refer call a method

前端 未结 4 1962
失恋的感觉
失恋的感觉 2020-12-09 03:53

I\'d like for an attribute call like object.x to return the results of some method, say object.other.other_method(). How can I do this?

Edi

4条回答
  •  有刺的猬
    2020-12-09 04:55

    Use the property decorator

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

    Mucking with the __dict__ is dirty, especially when @property is available.

提交回复
热议问题