Python: How to make object attribute refer call a method

前端 未结 4 2051
失恋的感觉
失恋的感觉 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:49

    This will only call other_method once when it is created

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

    Instead you could do this

    object.x = property(object.other.other_method)
    

    Which calls other_method everytime object.x is accessed

    Of course you aren't really using object as a variable name, are you?

提交回复
热议问题