简体   繁体   中英

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)

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM