Python property not set

Here is the code:

def Property(func): return property(**func()) class A: def __init__(self, name): self._name = name @Property def name(): doc = 'A' name' def fget(self): return self._name def fset(self, val): self._name = val fdel = None print locals() return locals() a = A('John') print a.name print a._name a.name = 'Bob' print a.name print a._name 

The following output is output above:

 {'doc': 'As name', 'fset': <function fset at 0x10b68e578>, 'fdel': None, 'fget': <function fget at 0x10b68ec08>} John John Bob John 

The code is taken here .

Question: what happened? It should be something simple, but I cannot find it.

Note. I need a property for complex getting / setting, and not just hiding an attribute.

Thanks in advance.

+6
source share
2 answers

The documentation for property() reads:

Returns the property attribute for the new style classes (classes that are inferred from the object).

Your class is not a new style class (you did not inherit from the object). Change the class declaration:

 class A(object): ... 

and he must work as intended.

+8
source

(above) Use this format: http://docs.python.org/library/functions.html#property

 class C(object): def __init__(self): self._name = "nameless" @property def name(self): """I'm the 'name' property.""" return self._name @name.setter def name(self, value): self._name = value @name.deleter def name(self): del self._name 
+1
source

Source: https://habr.com/ru/post/916701/


All Articles