一、_new_方法
创建实例时触发_new_方法
_new_方法会创建并返回实例
class Cls: instance = 0 #cls 规范命名 ,表示一个类 def __new__(cls, *args, **kwargs): if cls.instance == 0: #当标志值为0 cls.instance = super().__new__(cls) #调用父类的_new_并传入本类 #实例化,获取实例 #将实例赋值给当前类的instance属性 return cls.instance #返回当前类的instance属性 def __init__(self): print("初始化") c1 = Cls() c2 = Cls() # print(id(c1), id(c2)) # print(Cls.mro())
二、定制属性访问
class Cls: name = "我" def __setattr__(self, key, value): print("属性名:%s; 属性值:%s" % (key, value)) def __delattr__(self, item): print("删除%s" % item) def __getattribute__(self, item): print("获取%s" % item) return "111" def __getattr__(self, item): print("%s不存在" % item) c = Cls() # setattr(c, "name", "李坤") # print(c.name) # ss = getattr(c, "name") # print(ss) attr_bool = hasattr(c, "傻逼") print(attr_bool) # c.傻逼
三、描述符
#描述符 class A: def __get__(self, instance, owner): print("获取") def __set__(self, instance, value): print("修改") def __delete__(self, instance): print("删除") class B: ins = A() a = B() #当属性是一个实例的时候 #对这个属性 查 改 删 # print(a.ins) a.ins = 23 # del a.ins
四、装饰器
#内置装饰器 class Cls: @property def test01(self): print("调用") return "属性形式调用" @staticmethod def test02(name): print("不会自动传入self", name) @classmethod def test03(cls): print("自动传入类")
#类装饰器 class Cls: def __init__(self, func): print("初始化装饰器") self.fun = func def __call__(self, *args, **kwargs): print("执行被装饰的函数") self.fun( *args, **kwargs) @Cls def fun(name): print(name, "执行函数") aa = Cls("1111") fun("李坤")