Python 基础入门第十三讲 魔法方法补充、单例模式、reflect反射(getattr、hasattr、__import__())

本文介绍了Python中的几种重要魔法方法,包括__doc__(获取类的文档字符串)、__del__(析构方法)、__call__(使类实例可调用)、__dict__(查看类或对象成员)和__new__(创建对象)。还探讨了单例模式的实现以及通过getattr、hasattr和__import__进行的反射操作。文章通过实例帮助理解这些概念。
摘要由CSDN通过智能技术生成

第十三讲

一、特殊成员和魔法方法

在之前的课程中已经学习过如__ 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__()魔法方法

该方法也被称为析构方法,当对象在内存中被释放时,自动触发此方法。
注意三种情况:

  1. 全部代码执行完毕,自动触发__ del__();
  2. del 对象,主动触发__ del__();
  3. 仅有对象全部被释放,才会主动触发__ del__()。

我们通过例子来看一下:

class Demo(object):
	def __del__(self):
		print('I was deleted')
a = Demo()
###
执行结果:
I was deleted

上述代码在a实例化后就执行完毕了,自动触发del魔法方法,我们来做个对比更加清晰,充分理解第一种情况:

class 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值