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

这段代码返回错误: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()
Mohan Gulati asked 2019-10-09T07:33:07Z
1个解决方案
128 votes

这是你想要的吗?

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。]

Bastien Léonard answered 2019-10-09T07:33:27Z
translate from https://stackoverflow.com:/questions/1684828/how-to-set-attributes-using-property-decorators