如何使用属性装饰器设置属性?

时间:2009-11-06 01:27:34

标签: python

此代码返回错误:AttributeError:无法设置属性 这真的很可惜,因为我想使用属性而不是调用方法。有谁知道为什么这个简单的例子不起作用?

#!/usr/bin/python2.6


class Bar( object ):
    """ 
    ...
    """

    @property
    def value():
      """
      ...
      """    
      def fget( self ):
          return self._value

      def fset(self, value ):
          self._value = value


class Foo( object ):
    def __init__( self ):
        self.bar = Bar()
        self.bar.value = "yyy"

if __name__ == '__main__':
    foo = Foo()

1 个答案:

答案 0 :(得分:129)

这是你想要的吗?

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

取自http://docs.python.org/library/functions.html#property