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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> class Rectangle:
def __init__(self, x, y): #init方法初始化不带参数,因此我们需要重写init
self.x = x
self.y = y
def getPeri(self):
return (self.x + self.y) * 2
def getArea(self):
return self.x * self.y


>>> rect = Rectangle(3, 4)
>>> rect.getPeri()
14
>>> rect.getArea()
12

**We have to know the returned value of __init__() must be None.

1
2
3
4
5
6
7
8
9
10
>>> class A:
def __init__(self):
return "A"


>>> a = A()
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
a = A()
TypeError: __init__() should return None, not 'str'

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
2
3
4
5
6
7
8
9
10
# str is an unchangeable class, but we need to make all the input to become capitalization. So we need to use the __new__() to initialize.
>>> class CapStr(str):
def __new__(cls, string):
string = string.upper()
return str.__new__(cls, string)


>>> a = CapStr("I love Python!")
>>> a
'I LOVE PYTHON!'

__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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
>>> class C:
def __init__(self):
print("__init__ method is called.")
def __del__(self):
print("__del__ method is called.")


>>> c1 = C()
__init__ method is called.
>>> c2 = c1
>>> c3 = c2
>>> del c3
>>> del c2
>>> del c1
__del__ method is called.
>>> c4 = C()
__init__ method is called.
>>> c5 =c4
>>> del c4
>>> del c5
__del__ method is called.

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 协议 ,转载请注明出处!