Python之路- 反射&定制自己的数据类型

时间:2023-12-19 10:24:32

一.isinstance和issubclass

  • isinstance(obj,cls)检查是否obj是否是类 cls 的对象
  • issubclass(sub, super)检查sub类是否是 super 类的派生类
 class Foo:
pass
class Bar(Foo):
pass
f = Foo()
b = Bar()
print(isinstance(f,Foo))
print(issubclass(Bar,Foo))
print(isinstance(Bar,Foo))
print(isinstance(b,Foo))

输出结果如下

 True
True
False
True

二.反射和相关的内置函数

  • 反射是指程序可以访问、检测和修改它自己本身状态或者行为的一种能力(自省)。
  • 而在Python中,反射其实就是通过字符串的形式访问或者修改对象的属性。这里的对象是指一切对象,类本身也是一个对象。
 class People:
country = 'china'
def __init__(self,name,sex):
self.name = name
self.sex = sex
def walk(self):
print('walk')
p1 = People('silver_bullet','male')
print(hasattr(p1,'name')) #hasattr(*args, **kwargs) 验证有没有该属性
print(getattr(p1,'sex')) #getattr(object, name, default=None) 获取一个属性,可以设置default
print(setattr(p1,'age',22)) #setattr(x, y, v) 设置一个属性,返回值为None,所以用下面get方法验证
print(getattr(p1,'age'))
print(delattr(p1,'age')) #delattr(x, 'y') is equivalent to del x.y 删除一个属性,返回值为None
# print(getattr(p1,'age')) #age属性已经被删除掉
setattr(p1,'show_name',lambda self:self.name+' is excellent')#增加一个函数属性
print(p1.show_name(p1))

模块级别的反射

 import sys
xxx = 111
this_module = sys.modules[__name__] #获取当前模块
print(hasattr(this_module,'xxx'))
print(getattr(this_module,'xxx'))
setattr(this_module,'yyy','')
print(getattr(this_module,'yyy'))

反射的好处

  • 实现可插拔机制。可以事先定义好接口,接口只有在被完成后才会真正执行,这实现了即插即用,这其实是一种‘后期绑定’,即你可以事先把主要的逻辑写好(只定义接口), 然后后期再去实现接口的功能。

  • 动态导入模块(基于反射当前模块成员)。
 import importlib
t = importlib.import_module('time') #通过字符串的形式导入模块,推荐使用importlib
print(t.time()) #不推荐__import__(m),m为字符串,这个是python解释器自己使用的

三.内置函数(__attr__相关)

 class Foo:
'内置函数__attr__的使用'
def __init__(self,name):
self.name = name #这个也会触发__setattr__的执行
def __setattr__(self, key, value): #给属性赋值都会触发__setattr__,把key和value都赋值,可以做类型判断,弥补python没有类型限制
self.__dict__[key] = value #直接在dict字典中添加相应的键值对即可,key和value都为字符串
print('from __setattr__')
def __delattr__(self, item): #del 操作会触发这个内置函数
self.__dict__.pop(item) #直接在dict字典中删除相应的键值对即可
print('from __delattr__',type(item))# type(item)--------->str
def __getattr__(self, item): #注意:属性获取不到,才会触发这个内置函数!!!
print('get__attr__---->{0},{1}'.format(item,type(item))) f = Foo('silver_bullet') #触发__init__里就有一个赋值,即会触发__settattr__
f.time = 555
print(f.__dict__)
print(f.time)
del f.time #触发__del__内置函数
print(f.__dict__)
f.xxx #这个才会触发__getattr__的执行,没有找到xxx的属性,而现在却没有报错

四.定制自己的数据类型

  • 继承的方式

 class my_list(list):                   #基于继承
def __init__(self,seq):
for i in seq:
if not isinstance(i,str):
raise TypeError('This is not a str list')
else:
super().append(i)
def append(self, object: str):
if not isinstance(object,str):
raise TypeError('must be str')
super().append(object)
@property
def mid_value(self):
mid_index = len(self)//2
return self[mid_index] l = my_list(['a'])
print(l)
l.append('')
print(l)
print(l.mid_value)
l.insert(0,4)
print(l)
  • 授权的方式  

 class my_list():                                 #基于授权
def __init__(self,seq):
for i in seq:
if not isinstance(i,str):
raise TypeError('This is not a str list')
self.seq = list((seq)) #使用一个中间属性self.seq保存这个列表
def __str__(self): #override __str__,才能够打印列表的显示,否则打印的是一个对象地址
return str(self.seq)
def append(self, object: str): #重新定制这个append
if not isinstance(object,str):
raise TypeError('must be str')
self.seq.append(object) #实际上是在这里使用
@property
def mid_value(self): #定制一个属性,返回中间值。
mid_index = len(self.seq)//2
return self.seq[mid_index]
def __getattr__(self, item): #其余方法都使用list默认的
func = getattr(self.seq,item) #直接返回getattr的函数名
return func
def __getitem__(self, item): #加上以下三个item操作,才能够支持索引,切片,赋值和del删除
return self.seq[item]
def __setitem__(self, key, value):
self.seq[key] = value
def __delitem__(self, key):
self.seq.pop(key) l = my_list(['a'])
print(l)
l.append('')
print(l[1])
print(l.mid_value)
l.insert(0,4)
l[0]=''
print(l)
print(l[1:])

五.给日志文件加时间头

使用授权的方式重写open

 import time
class Open:
'override File write'
def __init__(self,path,mode = 'r',encoding = 'GBK'):
self.fw = open(path,mode=mode,encoding=encoding) #这里要写成位置参数的形式,取到文件句柄赋值给self.f
def write(self,line):
now_time = time.strftime('%Y-%m-%d-%X') #字符串形式显示time时间
self.fw.write('{0}\n'.format(now_time)) #添加日志文件的时间头
self.fw.write(line) #写想要输入到文件里面的内容
def __getattr__(self, item): #不想要改写的地方定义在__getattr__中,找不到的属性会触发这个内置函数
func = getattr(self.fw,item) #通过getattr的方法,将函数名的入口地址获取到并且返回
return func f = Open('a.txt','w+') #触发__init__方法
for i in range(2):
f.write('11111111111\n')
time.sleep(0.5)
f.seek(0)
print(f.readlines())