第十三讲
一、特殊成员和魔法方法
在之前的课程中已经学习过如__ init__、__ str__、__dir__等魔法方法,现补充一些常用的魔法方法:
1. __ doc__ 魔法方法
该魔法方法的作用为打印类的说明文档,举个例子:
print(str().__doc__)
###
输出结果为:
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
这是我们常用的str类的解释说明文档,如果我们要查看类的解释说明文档,需要键入class().__doc__
的格式,并打印输出即可。我们自己建立的新类也可以实现相同的操作:
class Demo(object):
'''
Here is the explanation for the Demo.
'''
pass
a = Demo()
print(a.__doc__)
print(Demo().__doc__)
注意一下,当我们实例化对象后,上述两个语句均可以打印输出说明文档。
2. __ del__()魔法方法
该方法也被称为析构方法,当对象在内存中被释放时,自动触发此方法。
注意三种情况:
- 全部代码执行完毕,自动触发__ del__();
- del 对象,主动触发__ del__();
- 仅有对象全部被释放,才会主动触发__ del__()。
我们通过例子来看一下:
class Demo(object):
def __del__(self):
print('I was deleted')
a = Demo()
###
执行结果:
I was deleted
上述代码在a实例化后就执行完毕了,自动触发del魔法方法,我们来做个对比更加清晰,充分理解第一种情况:
class