python中魔法方法

mac2022-06-30  26

1. python中的魔法方法, 类似__init__, __str__等等,这些内置好的特定的方法进行特定的操作时会自动被调用

 

2. __init__的使用方法

class 类名(object):    def __init__(self):        print("hhahhah")对象1 = 类名()

打印结果:hhahhah

说明init的方法实例化对象的时候会自动初始化调用

 

3. __str__的使用方法

class 类名(object):    def __str__(self):

return "hello world"对象1 = 类名()print(对象1)

打印结果:hello world

说明__str__方法会重写原来的方法重写返回自定义的代码

 

4. __del__的方法使用

class 类名(object):    def __del__(self):        print("%s已经在内存中消失"%self)对象1 = 类名()del(对象1)print("程序最后的代码")

打印输出:

__main__.类名 object at 0x000002B9AA1BC160>已经在内存中消失

程序最后的代码

 

说明__del__的方法会在创建的对象消失后运行

转载于:https://www.cnblogs.com/valorchang/p/11471159.html

最新回复(0)