python new和init方法

__new__方法,构造实例方法。构造好实例后,调用__init__方法,初始化对象

 1 class MyClass:
 2     # 构造方法
 3     def __new__(cls, *args, **kwargs):
 4         print("new func")
 5         return 29
 6 
 7     # 初始化方法
 8     def __init__(self, age: int):
 9         # self.age = age
10         print("init func")
11 
12 
13 my_class = MyClass(18)
14 print(my_class)
15 # print(my_class.age)
 1 class Single:
 2     def __new__(cls, *args, **kwargs):
 3         if not hasattr(cls, 'instance'):
 4             cls.instance = super(Single, cls).__new__(cls)
 5         return cls.instance
 6 
 7     def __init__(self, age: int):
 8         self.age = age
 9 
10 obj1 = Single(18)
11 obj2 = Single(19)
12 print(obj1 is obj2)
13 print(obj1.age)
14 print(obj2.age)

 

posted on 2026-01-15 00:19  luckygxf  阅读(3)  评论(0)    收藏  举报

导航