1

I was reading this post and few things don't get cleared

https://stackoverflow.com/a/14787522/1890488

He uses this code

class O4(O3):
    @property # this decorator makes this instancevar into a data descriptor
    def var(self):
        return "Data descriptors (such as properties) are high priority"

    @var.setter # I'll let O3's constructor set a value in __dict__
    def var(self, value):
        self.__dict__["var"]  = value # but I know it will be ignored

He says that @property converts any instance variable into data descriptor.

  1. Now does it mean that it automatically defines __get__ , __set__ and __del__ for that varaible

or @property is only equivalent to __get__

i am not getting it

  1. Are there any more decorators which convert instance variables to data descriptors

  2. what is the function of @var.setter. is that also the data descriptor part

Community
  • 1
  • 1
user2024264
  • 349
  • 1
  • 5
  • 12

2 Answers2

1

The @property calls the property() builtin, and you should consult the documentation for details of that.

property only has one mandatory parameter, the leftmost, the "getter". Others are setter and deleter.

The use of a decorator with the @ prefix is only syntactic sugar. If you wish you can call property in a more conventional (if unpythonic) way:

def var_get(self):
    return "Data descriptors (such as properties) are high priority"

def var_set(self, value):
    self.__dict__["var"]  = value 

var = property(var_get, var_set)
cdarke
  • 42,728
  • 8
  • 80
  • 84
0

If you look at the code for the property decorator on your system, you'll see that it takes three arguments:

  • fget: A function that does the getting of the variable;
  • fset: A function that does the setting of the variable;
  • fdel: A function that deletes the variable.

As you normally decorate a single function with a decorator, you'll usually just define the getter:

@property
def my_var(self):
    return self._my_var

Should you wish to also declare a setter, you can use your new 'property' to include a setter, via .setter:

@my_var.setter
def my_var(self, value):
    self._my_var = value

The combination of the two is equivalent to calling my_var = property(get_my_var, set_my_var).

akaIDIOT
  • 9,171
  • 3
  • 27
  • 30
  • From the `property` doc: *Be sure to give the additional functions the same name as the original property*. Your `set_my_var` will give an AttributeError when used as a setter. – cdarke Feb 11 '13 at 09:27
  • Your equivalent call to `property` is also suspect, since you replace `my_var` (referencing a function) with the return value of `property`. If you are not using decorators then the function names have to be different to the attribute name. With decorators they all use the same name. – cdarke Feb 11 '13 at 10:58
  • While overwriting the variable works just fine, I've changed things to be more explicit :) – akaIDIOT Feb 11 '13 at 11:58