Is setattr calling property setter func?

Viewed 475

I try to fit good oop behaviour in my code and was wondering the following:

I generally have this kind of a class design:

class MyClass():
    def __init__(self,arg1):
        self.arg1 = arg1

    @property
    def arg1(self):
        return _arg1

    @arg1.setter
    def arg1(self, value):
        self._arg1 = value

If I now write a function which has a dict and uses this dict for setting class attributes:

    def set_my_dict(self):
        argdict = {'arg1':4}
        for k, v in argdict:
            setattr(self, k, v)

Does this setattr call, in this situation, the setter for possible type checks etc?

1 Answers

I was interested as well, so i opened up ipython and added pdb to the setter method to test.

In [5]: class MyClass():
   ...:     def __init__(self,arg1):
   ...:         self.arg1 = arg1
   ...: 
   ...:     @property
   ...:     def arg1(self):
   ...:         return _arg1
   ...: 
   ...:     @arg1.setter
   ...:     def arg1(self, value):
   ...:         import pdb;
   ...:         pdb.set_trace();
   ...:         self._arg1 = value
   ...: 

In [6]: xr = MyClass(2)
> <ipython-input-5-21bab018f5a2>(13)arg1()
-> self._arg1 = value
(Pdb) c

In [7]: setattr(xr, "arg1", 3)
> <ipython-input-5-21bab018f5a2>(13)arg1()
-> self._arg1 = value
(Pdb) c

The setter function is used at both at instantiation and when using the setattr. neat.

Related