isinstance,issubclass
isinstance:判断对象是否为这个类实例化出来的(会检测父类)
type:获取实例化出对象的类(不会检测父类)
class Foo:
pass
class Bar(Foo):
pass
b=Bar()
print(isinstance(b,Foo)) # True
print(isinstance(b,Bar)) # True
print(type(b)==Foo) # Fasle
print(type(b)==Bar) # True
issubclass:比较判断某个类是否为另一个类的子类
print(issubclass(Bar,Foo)) # True
反射
hasattr:通过字符串判断是否类属性存在
getattr:通过字符串获取类属性
setattr:通过字符串修改类属性
delattr:通过字符串删除类属性
class Foo:
count=0
def eat(self):
print('eat')
f=Foo()
if hasattr(f,'eat'): # 判断有没有
getattr(f,'eat')() # 获取
setattr(f,'ear',222) # 修改自己,没有就添加
setattr(f,'count',111)
delattr(f,'count') # 删除
print(f.__dict__)
项目中可能用到
import sys
import time
# comment.py 通用评论接口
# import goods,shopping_car 导入其他文件
mod=sys.modules['__main__']
arg==input('goods.py或shopping_car.py给comment.py的参数)
if arg=='goods':
tim=getattr(mod,'goods',None)
# 2287273393
# return comment
elif arg=='shoppings_car':
tim=getattr(md,'goods',None)
# 150
#return comment
call
class Foo:
def __init__(self):
print('Foo()会触发我')
def __call__(self):
print('Foo()()/f()会触发我')
f = Foo() # 对象再加括号调用触发
f()
元类
元类用来造类的
元类()-->类-->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
单例模式
利用类的绑定方法的特性
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()
利用装饰器
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()
利用元类(正宗的)
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()
异常处理
捕捉异常
x = 10
y = 20
c = 30
try:
1/0
except Exception as e:
print(e)
raise
raise keyboardInterrupt('中断捕捉')
assert
判断某一行代码是否有问题