Search code examples
pythonclassvariablesmembers

Setting a variable python class - function


Is there a function such that i can write but as a function?

class foo:
    def __init__(self,x):
        self.x = x;

asd = foo(2);
asd.x = 5;
print(asd.x);

But like:

class foo:
    def __init__(self,x):
       self.x = x;
    def someFunction(self,string,value):
        if(string == 'x'):
           self.x = value;
           print("worked");

 asd = foo(2);
 asd.x = 3; #and "worked" will be printed?

I tried __ set __ and __ setattr __ but i had no luck ;\

Is there a way to call a function when setting a class variable? asd.x = 3; calls a function?


Solution

  • Use a property. The method decorated by @property will be used whenever you try to access the attribute x; the method subsequently decorated by @x.setter will be called whenever you try to set the value of x. The underlying "private" attribute _x is used to store the value for x used by both the getter and setter.

    class foo:
    
        @property
        def x(self):
            return self._x
    
        @x.setter
        def x(self, value):
            self._x = value
            print("worked")
    
        def __init__(self, x):
            self._x = x
    

    The decorator syntax can be skipped if you want more explicit names for the getter and setter methods:

    class foo(object):
    
        def __init__(self, x):
             self._x = x
    
        def _get_x(self):
            return self._x
    
        def _set_x(self, value):
            self._x = value
            print("worked")
    
        x = property(_get_x, _set_x)