Python: How to make object attribute refer call a method

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

    Have a look at the built-in property function.

    0 讨论(0)
  • 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?

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-09 04:56

    Use a 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
    
    0 讨论(0)
提交回复
热议问题