Python:如何使对象属性引用调用方法

mel*_*ort 18 python attributes

我想要一个属性调用,比如object.x返回一些方法的结果object.other.other_method().我怎样才能做到这一点?

编辑:我很快就问了一下:看起来我可以这样做

object.__dict__['x']=object.other.other_method()
Run Code Online (Sandbox Code Playgroud)

这是一个好方法吗?

Don*_*ner 35

使用属性装饰器

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

p = Test()
p.x # returns 4
Run Code Online (Sandbox Code Playgroud)

使用__dict__进行捣乱是很脏的,特别是当@property可用时.


小智 11

看看内置属性函数.


Gar*_*err 5

用一个 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
Run Code Online (Sandbox Code Playgroud)