Magic Methods 4
Magic Methods: Attribute Access
We can use the “.” operator to access the attribute. Also, we can use the magic methods to access it.
For example : We can use “.”, getattr() to access it.
1 |
|
We use this to link the x and the size in below.
1 |
|
The magic methods to access attribute :
Magic Methods | Definition |
---|---|
__getattr__(self, name) | 定义当试图获取一个不存在的属性时的行为 |
__getattribute__(self, name) | 定义当类的属性被访问时的行为 |
__setattr__(self, name) | 定义当一个属性被设置时的行为 |
__delattr__(self, name) | 定义当一个属性被删除时的行为 |
先访问getattribute,如果有值返回值,没有返回getattr的内容。
Try
- Define a rectangle class, which defaults with width and height.
- Define a square attribute, the returned value is the length of side, and declare the square.
Endless Loop :
1 |
|
In this part, the endless loop is resulted by the evaluation. In the ‘int’ magic methods, ‘self.width = width’ will call the ‘setattr’ methods. In the ‘setattr’, there is evaluation again, which leads to the endless loop.
-> Endless iteration
We need to be careful about the endless iteration of accessing attribute. Try the ‘super()’ to call the base class to avoid the endless loop.
In the code above, we can change the Line 11, ‘self.name = value’ to ‘super().__setattr__(name, value)’ or ‘self.__dict__[name] = value’. The first one is recommended.
Here is the result after modification.
1 |
|
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!