Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set attributes using property decorators?

Tags:

python

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()
like image 425
Mohan Gulati Avatar asked Nov 06 '09 01:11

Mohan Gulati


People also ask

How do you set attributes in Python?

Use the setattr() Function to Set Attributes of a Class in Python. Python's setattr() function is used to set values for the attributes of a class. In programming, where the variable name is not static, the setattr() method comes in very handy as it provides ease of use.

What is use of property decorator with example?

@property decorator is a built-in decorator in Python which is helpful in defining the properties effortlessly without manually calling the inbuilt function property(). Which is used to return the property attributes of a class from the stated getter, setter and deleter as parameters.

What does @property mean in Python?

The @property is a built-in decorator for the property() function in Python. It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.


1 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.

like image 187
Bastien Léonard Avatar answered Oct 08 '22 02:10

Bastien Léonard