How can I call a Python (v2.7) setter property from inside __init__
? I written the following class but I dont know how to change it to make it work. I get an AttributeError: 'test' object has no attribute '_x'
exception. There are a few similar questions around here but couldnt find an answer so far. The idea is when the initialiser is called to do some processing/slicing and assign the result to an attribute
class test(object):
def __init__(self, a,b):
self._x = self.x(a,b)
@property
def x(self):
return self._x
@x.setter
def x(self, a, b):
self._x = "Get this from {} and make a dataframe like {}".format(a,b)
The __init__ function is called every time an object is created from a class. The __init__ method lets the class initialize the object's attributes and serves no other purpose.
Getters and Setters in python are often used when: We use getters & setters to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user.
The @property Decorator In Python, property() is a built-in function that creates and returns a property object. The syntax of this function is: property(fget=None, fset=None, fdel=None, doc=None) where, fget is function to get value of the attribute. fset is function to set value of the attribute.
self.x
is a property, so you'd just assign directly to it like you would with a regular attribute:
def __init__(self, a, b):
self.x = (a, b)
However, the setter is given one object, always; in the above case, it is passed a tuple; you could unpack it:
@x.setter
def x(self, value):
a, b = value
self._x = "Get this from {} and make a dataframe like {}".format(a,b)
Note the value
argument; that's the result of the assignment being passed to the setter.
Demo:
>>> class test(object):
... def __init__(self, a, b):
... self.x = (a, b)
... @property
... def x(self):
... return self._x
... @x.setter
... def x(self, value):
... a, b = value
... self._x = "Get this from {} and make a dataframe like {}".format(a,b)
...
>>> t = test(42, 'foo')
>>> t.x
'Get this from 42 and make a dataframe like foo'
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