0

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?

Sanavesa
  • 13
  • 2

2 Answers2

0

For an object to handle setting of attributes on itself, use the __setattr__ method. It's rather tricky to debug, so don't do this unless you know what you're doing. Good explanation

source

class Beer(object):
    def __init__(self, adj):
        self.adj = adj

    def __setattr__(self, key, value):
        print '\tSET',key,value
        object.__setattr__(self, key, value)  # new style (don't use __dict__)

b = Beer('tasty')
print 'BEFORE',b.adj
b.adj = 'warm'
print 'AFTER',b.adj
print b.__dict__

output

    SET adj tasty
BEFORE tasty
    SET adj warm
AFTER warm
{'adj': 'warm'}
Community
  • 1
  • 1
johntellsall
  • 14,394
  • 4
  • 46
  • 40
0

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)
chepner
  • 497,756
  • 71
  • 530
  • 681