定制自己的数据类型

Posted study_python

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了定制自己的数据类型相关的知识,希望对你有一定的参考价值。

#继承
"""
class LIST(list):
def append(self, p_object):
if not isinstance(p_object,int):
raise TypeError(‘must be int‘)
super().append(p_object)

def insert(self, index, p_object):
if not isinstance(p_object,int):
raise TypeError(‘must be int‘)
super().insert(index,p_object)

li =LIST([1,2,3])
print(li)
#li.append(‘2‘)
li.append(4)
print(li)
li.insert(0,-10)
print(li)
#li.insert(0,‘-1‘)
print(li)
"""
#授权
import time
class Open:
def __init__(self,filepath,m=‘w+‘,encode=‘utf-8‘):
self.filepath =filepath
self.mode =m
self.encoding =encode
self.x =open(filepath,mode =m,encoding=encode)
def write(self,line):
t =time.strftime(‘%Y-%m-%d %X‘)
self.x.write(‘%s %s‘%(t,line))


def __getattr__(self, item):
print(‘%s %s‘%(self,item))#getattr(self.x,item),中的item是字符串
return getattr(self.x,item)#把它转化成self.x.item(属性),
#print(‘%s %s‘(self))
f =Open(‘a‘)
f.write(‘12112121\n‘)
f.write(‘121212121\n‘)
f.seek(0)
print(f.read)#查询f.read,但是没有找到,f.read,所以就触发__getattr__方法

以上是关于定制自己的数据类型的主要内容,如果未能解决你的问题,请参考以下文章

定制自己的数据类型

爱根,征服我的一天[isinstance,issubclass]反射内置attr,定制自己的数据类型

Python面向对象进阶示例--自定义数据类型

面向对象,为对象定制自己独有的属性, 属性查找, 绑定方法, 类即类型, 继承与派生, 继承的应用

包装和授权

第十八章 定制特性