#new方法
###__new__构造方法
#先执行new方法,再init方法;先构造,再初始化
#平常不写new方法,是因为类默认继承object类,本类没有new方法就去object类里找new方法并执行
#自己有new方法,就不会再去object类里找了
class Student:#默认继承object
def __new__(cls, *args, **kwargs):
print('执行***')
obj= object.__new__(cls)
print(obj)
return obj
def __init__(self):#初始化的方法,前面还有一部,构造方法
#self就是new方法创造的对象
print(self) #self就是obj
print('执行。。。')
alex=Student() #python 解释器接收到 翻译成C语言的字节码 解释成机器码
#单例模式
单例模式:某一个类只有一个实例,只能实例化一个对象
#23种设计模式
#创造任何对象,都会走new,init方法
class Person:
__isinstance=None
def __new__(cls, *args, **kwargs):
if not cls.__isinstance:
obj=object.__new__(cls)
cls.__isinstance=obj
return cls.__isinstance
def __init__(self,name):
self.name=name
alex=Person('alex')
egon=Person('egon')
print(id(alex),id(egon))#打印下地址
print(alex.name,egon.name)
#打印结果:
39091280 39091280
egon egon