Python之__new__方法

 1 # -*- coding: utf-8 -*-
 2 """
 3 Created on Sun Dec  2 11:03:03 2018
 4 Python类构造过程
 5 @author: zhen
 6 """
 7 
 8 class Man(object):
 9     
10     def __new__(cls):  # 当子类重写父类的__new__方法时,会首先执行__new__方法创建对象
11         print("--new--")
12         return object.__new__(cls)  # 需要调用父类创建对象
13         
14     def __init__(self):  # __init__方法执行内部需要传入__new__返回的对象
15         self.name = "Python"
16         self.age = 18
17         print("--init--")
18     
19     def __str__(self):  # 类似Java中的toString()方法,用于结构化输出
20         print(self.name, self.age)
21         
22     def __del__(self):  # 对象生命周期结束时调用
23         print("--del--")
24         
25 man = Man()

结果:

猜你喜欢

转载自www.cnblogs.com/yszd/p/10052678.html