Why to use __setattr__ in python?

后端 未结 7 1193
隐瞒了意图╮
隐瞒了意图╮ 2020-12-16 11:12

I don\'t know for why using __setattr__ instead simple referencing like x.a=1.

I understand this example:

class Rectangle:         


        
相关标签:
7条回答
  • 2020-12-16 11:49

    __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)
    
    0 讨论(0)
提交回复
热议问题