Aenaon
Aenaon

Reputation: 3593

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)

Upvotes: 27

Views: 21318

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1125078

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'

Upvotes: 35

Related Questions