Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

call a setter from __init__ in Python

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)
like image 486
Aenaon Avatar asked Mar 08 '16 21:03

Aenaon


People also ask

Why is it called __ init __?

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.

What is the most pythonic way to use getter and setter?

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.

What is @property in Python?

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.


1 Answers

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'
like image 150
Martijn Pieters Avatar answered Oct 01 '22 15:10

Martijn Pieters