I don\'t know for why using __setattr__
instead simple referencing like x.a=1
.
I understand this example:
class Rectangle:
__setattr__
is a class method that is called by setattr
builtin method. That is, if __setattr__
is defined in given class. Most often you do not declare your own version of __setattr__
so I assume you are asking of what use is the setattr
method.
Suppose you have a var with the name of the attribute you want to set instead of just knowing the name:
class A(object):
def doSth(self, name, val):
setattr(self, name, val)
impossible to do with self.name = val
Also, a common usage is with keyword args:
class A(object):
def __init__(self, *args, **kwargs):
for k,v in kwargs.items():
setattr(self, k, v)