面向对象高级
一、面向对象高级小结
1.1 isinstance,issubclass
isinstance判断是否为类的实例化对象,会检测父类,而type不会检测父类
issubclass,判断是否为其子类
1.2 反射
- hasattr:通过字符串判断是否类属性存在
- getattr:通过字符串获取类属性
- setattr:通过字符串修改类属性
- delattr:通过字符串删除类属性
1.3 call
class Foo:
def __init__(self):
print('Foo()会触发我')
def __call__(self):
print('Foo()()/f()会触发我')
f = Foo()
f()
1.4 new
class Foo:
def __new__(self):
print('new')
obj = object.__new__(self)
return obj
def __init__(self):
print('init')
f = Foo()
1.5 元类
元类用来造类的
元类()-->类-->init
元类()()-->对象--->call
类分为几部分:类名/类体名称空间/父类们
class Mymeta(type):
def __init__(self,class_name,class_bases,class_dic):
# 控制类的逻辑代码
super().__init__(class_name,class_bases,class_dic)
def __call__(self,*args,**kwargs):
# 控制类实例化的参数
obj = self.__new__(self) # obj就是实例化的对象
self.__init__(obj,*args,**kwargs)
print(obj.__dict__)
# 控制类实例化的逻辑
return obj
class People(metaclass=Mymeta):
def __init__(self,name,age):
self.name = name
self.age = age
二、单例模式
2.0.1 利用类的绑定方法的特性
NAME = 'nick'
AGE = 18
class People():
__instance = None
@classmethod
def from_conf(cls):
if cls.__instance:
return cls.__instance
cls.__instance = cls(NAME,AGE)
return cls.__instance
People.from_conf()
People.from_conf()
2.0.2 利用装饰器
NAME = 'nick'
AGE = 18
def deco(cls):
cls.__instance = cls(NAME,AGE)
def wrapper(*args,**kwargs):
if len(args) == 0 and len(kwargs) == 0:
return cls.__instance
res = cls(*args,**kwargs)
return res
return wrapper
@deco
class People():
def __init__(self,name,age):
self.name = name
self.age = age
peo1 = People()
peo2 = People()
2.0.3 利用元类(正宗的)
NAME = 'nick'
AGE = 18
class Mymeta(type):
def __init__(self,class_name,class_bases,class_dict):
super().__init__(class_name,class_bases,class_dict)
self.__instance = self(NAME,AGE)
def __call__(self,*args,**kwargs):
if len(args) == 0 and len(kwargs) == 0:
return self.__instance
obj = object.__new__(self)
self.__init__(obj,*args,**kwargs)
return obj
class People(metaclass=Mymeta):
def __init__(self,name,age):
self.name = name
self.age = age
peo1 = People()
peo2 = People()