【问题标题】:Python: How to make object attribute refer call a methodPython:如何使对象属性引用调用方法
【发布时间】:2010-07-02 14:51:53
【问题描述】:

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

编辑:我很快就问了:看起来我可以用

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

这是一种可行的方法吗?

【问题讨论】:

  • Re:您的编辑——是和否……您的解决方案将在object.x存储object.other.other_method() 的结果,这意味着该方法只会被调用一次,不是每次都读取object.x。如果您希望每次都调用该方法,@muksie 是正确的 — 查看 property 装饰器。

标签: python attributes


【解决方案1】:

使用属性装饰器

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

p = Test()
p.x # returns 4

使用 __dict__ 很脏,尤其是当 @property 可用时。

【讨论】:

  • 有没有办法动态地做到这一点?
  • 给出的例子没有解决“设置属性”的场景。
【解决方案2】:

看看内置的property函数。

【讨论】:

    【解决方案3】:

    使用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
    

    【讨论】:

      【解决方案4】:

      这只会在创建时调用other_method一次

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

      你可以这样做

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

      每次访问object.x 时都会调用other_method

      当然,您并没有真正使用object 作为变量名,是吗?

      【讨论】:

      • 当使用object.x = property(object.other.other_method)这个选项时,我在访问x属性时得到<property at 0x1941f02cf48>,我应该怎么做?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-11
      • 2021-12-15
      相关资源
      最近更新 更多