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

72 投票
1 回答
56574 浏览
提问于 2025-04-15 15:43

这段代码出现了一个错误:AttributeError: can't set attribute。真让人失望,因为我想用属性来代替调用方法。有没有人知道为什么这个简单的例子不管用呢?

#!/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 个回答

161

这就是你想要的吗?

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

撰写回答