How to set attributes using property decorators?

Question:

This code returns an error: AttributeError: can’t set attribute
This is really a pity because I would like to use properties instead of calling the methods. Does anyone know why this simple example is not working?

#!/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()
Asked By: Mohan Gulati

||

Answers:

Is this what you want?

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

Taken from http://docs.python.org/library/functions.html#property.

Answered By: Bastien Léonard
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.