Here is the code:
def Property(func):
return property(**func())
class A:
def __init__(self, name):
self._name = name
@Property
def name():
doc = 'A''s 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
Above produces the following output:
{'doc': 'As name', 'fset': <function fset at 0x10b68e578>, 'fdel': None, 'fget': <function fget at 0x10b68ec08>}
John
John
Bob
John
The code is taken from here.
Question: what's wrong? It should be something simple but I can't find it.
Note: I need property for complex getting/setting, not simply hiding the attribute.
Thanks in advance.
Creating Attributes With property() You can create a property by calling property() with an appropriate set of arguments and assigning its return value to a class attribute. All the arguments to property() are optional. However, you typically provide at least a setter function.
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.
Attributes are described by data variables for example like name, age, height etc. Properties are special kind of attributes which have getter, setter and delete methods like __get__, __set__ and __delete__ methods.
Python property() function returns the object of the property class and it is used to create property of a class. Parameters: fget() – used to get the value of attribute. fset() – used to set the value of attribute.
The documentation for property()
states:
Return a property attribute for new-style classes (classes that derive from object).
Your class is not a new-style class (you didn't inherit from object). Change the class declaration to:
class A(object):
...
and it should work as intended.
(Posted 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With