1、__new__方法:在创建对象的时候都会调用__new__方法进行,对象的创建
重写__new__方法:一定要调用父类的new方法
def __new__(cls,*args,**kwarags):
#cls 类对象的本身
print("-----new方法----")
return object.__new__(cls)
重写的实例:单例模式
class MyTest():
instance = None
def __new__(cls,*args,**kwarags):
if not cls.instance:
cls.instance = object.__new__(cls)
return cls.instance
else:
return cls.instance
t1= MyTest()
t1.nane = 'Mr_known'
t2= MyTest()
print(t2.name)
>>> Mr_known
用装饰器的方式实现类的单例模式
def single(cls):
instance= {}
def fun(*args, **kwargs):
if cls in instance:
return instance[cls]
else:
instance[cls] = cls(*args, **kwargs)
return instance[cls]
return fun
@single # MyTest= single(MyTest)
class MyTest():
pass
@single # Test = single(Test)
class Test():
pass
t1= MyTest()
t1.name = "Mr_known"
T2= Test()
print(T2.name)
把类当作装饰器:
class test():
def __init__(self,func):
self.func= func
def __call__(self,*arge,**kwargs):
print("装饰器里面的功能")
self.func()
@test test01 = test(test01) # 相当于创建了test 类的对象,
def test01():
print("这是test01")
test01() # 调用函数,相当于调用一个对象,一个对象可以被调用,就得定义__call__方法
2、__str__和__repr__方法
注意:在重写这两个方法时,一定要返回一个字符串
3、