Why to use __setattr__ in python?

后端 未结 7 1234
隐瞒了意图╮
隐瞒了意图╮ 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:37

    the __setattr__ can be used to reflection, where an propperty on the object Rectangle can be created at runtime, there are more about it on http://en.wikipedia.org/wiki/Reflection_%28computer_science%29

    class Rectangle:
        def __init__(self):
            #... code ...
    
    x = Rectangle()
    #x.__setattr__('newProperty',30)      Edited after comment
    setattr(x, 'newProperty', 30)
    print x.newProperty #>>> 30
    

提交回复
热议问题