Magic Methods-1
Magic Methods 1: Construction & Destruction
中文释义 : 构造和析构。
In this part, we will introduce three magic methods about construction and destruction. They are init, new and del.
__init__(self[,…])
1 |
|
**We have to know the returned value of __init__() must be None.
1 |
|
When we do the initialization, we use this magic method. Also, no returned value is obligatory for this method.
__new__(cls[,…])
Actually, we use the __new__() before initialization. Normally, the magic method is automatically called if we don’t rewrite it. The returned value of this method is a instantiated object*(实例化对象)*. This magic method is to be rewritten only when the we need to inherit an unchangeable class and we need to change the class to have some other function. [继承一个不可变类型又需要修改的时候]
For example :
1 |
|
__del__(self)
This magic method is for destruction. When we need to delete an object, the __del__() is automatically used. But we need to focus this :
del x is not equal to x.del().
1 |
|
Here is one point. **The rubbish mechanism is called when all the reference to the method is deleted. ** It is not called every time when the instantiated object is deleted.
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!