Python:如何让对象属性调用一个方法

24 投票
4 回答
23523 浏览
提问于 2025-04-16 00:44

我想让像 object.x 这样的属性调用返回某个方法的结果,比如 object.other.other_method()。我该怎么做呢?

编辑:我问得有点早:看起来我可以这样做

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

这样做可以吗?

4 个回答

6

使用一个 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
11

看看Python里内置的property函数。

50

使用属性装饰器

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

p = Test()
p.x # returns 4

直接修改 __dict__ 这个东西不太好,特别是当我们可以使用 @property 的时候。

撰写回答