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?

4
  • self.x and asd.x are the same thing, why do you want to differentiate between them? Commented Jun 3, 2014 at 16:12
  • stackoverflow.com/questions/3798835/… Commented Jun 3, 2014 at 16:13
  • you probably need to declare an @property Commented Jun 3, 2014 at 16:16
  • Either use a @property, or replace print("Worked") with return "Worked" Commented Jun 3, 2014 at 16:17

2 Answers 2

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)
Sign up to request clarification or add additional context in comments.

Comments

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'}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.