概述
学过C++/JAVA的同学都知道面向对象中有 构造方法,作用就是创建对象(实例化对象),并且初始化属性
在 Python 中, 创建对象 用__new__(cls) 实现
初始化属性用__init__(self)实现
__new__() 特点
类的 内置静态方法,不用
@staticmethod标注
第一个形参是 cls,表示 类本身如果类中定义了
__new__()方法,创建对象时,先调用__new__()方法如果类中没有
__new__()方法,那么会调用父类的__new__()方法在
__new__()方法中,通过父类的__new__()方法创建对象必须要 返回对象。(否则不会调用
__init__()方法,也 不会报错)创建对象后,才调用
__init__()方法。参数 self 就是__new__()方法返回的实例
例子
__new__()和__init__()执行顺序
class Phone:
def __new__(cls):
print("执行__new__()")
# 通过父类的__new__()创建对象
obj=super().__new__(cls)
print(obj)
return obj
def __init__(self):
print("执行__init__()")
print(self)
iphone=Phone()
执行结果如下:
执行__new__()
<__main__.Phone object at 0x0000007248428C88>
执行__init__()
<__main__.Phone object at 0x0000007248428C88>
总结:
在调用
Phone()时,先执行__new__(),后执行__init__()两个方法的对象地址相同,说明是同一个对象
__new__()不返回对象
class Phone:
def __new__(cls):
print("执行__new__()")
obj=super().__new__(cls)
print(obj)
# return obj
def __init__(self):
print("执行__init__()")
print(self)
iphone=Phone()
执行结果如下:
执行__new__()
<__main__.Phone object at 0x0000007BF98D8C88>
只执行了__new__()方法
创建对象时传入参数
在创建对象时,要传入手机名字参数,如下:
iphone=Phone("iphone11")
定义类的方式如下:
class Phone:
def __new__(cls,name):
print("执行__new__(%s)"%name)
return super().__new__(cls)
def __init__(self,name):
self.name=name
print("执行__init__(%s)"%name)
iphone=Phone("iphone11")
print(iphone.__dict__)
执行结果如下:
执行__new__(iphone11)
执行__init__(iphone11)
{'name': 'iphone11'}