暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

python扩展内置类型

原创 梯阅线条 2023-12-17
152

1 python扩展内置类型

python类可用于扩展内置类型,支持更复杂的数据结构。

1.1 通过嵌入扩展类型

python通过定义一个集合类实例化集合对象,定义交集、并集方法,重载运算符,来扩展一个内置类型。比如,包装一个列表。

setwrapper.py

class Set: def __init__(self,value=[]): self.data=[] self.concat(value) def intersect(self,other): res=[] for x in self.data: if x in other: res.append(x) return Set(res) def union(self,other): res=self.data[:] for x in other: if not x in res: res.append(x) return Set(res) def concat(self,value): for x in value: if not x in self.data: self.data.append(x) def __len__(self):return len(self.data) def __getitem__(self,key):return self.data[key] def __and__(self,other):return self.intersect(other) def __or__(self,other):return self.union(other) def __repr__(self):return 'Set:'+repr(self.data)

在idle执行下面语句

>>> import os >>> os.chdir(r'E:\documents\F盘') >>> from setwrapper import * >>> s=Set([1,3,5,7]) >>> print(s.intersect([3,5,9])) Set:[3, 5] >>> print(s.union([3,5,9])) Set:[1, 3, 5, 7, 9] >>> print(s|Set([1,2,3])) Set:[1, 3, 5, 7, 2]

1.2 通过子类扩展类型

python通过继承内置类型来扩展指定类型达到定制的效果。

比如,继承列表list,修改下标从1开始。

typesubclass.py

class MyList(list): def __getitem__(self,offset): print('(indexing {0} at {1})'.format(self,offset)) return list.__getitem__(self,offset-1)

在idle执行下面语句

>>> import os >>> os.chdir(r'E:\documents\F盘') >>> print(list('梯阅线条')) ['梯', '阅', '线', '条'] >>> from typesubclass import * >>> ml=MyList('梯阅线条') >>> print(ml) ['梯', '阅', '线', '条'] >>> print(ml[1]) (indexing ['梯', '阅', '线', '条'] at 1) 梯 >>> print(ml[3]) (indexing ['梯', '阅', '线', '条'] at 3) 线 >>> ml.append('t') >>> print(ml) ['梯', '阅', '线', '条', 't'] >>> ml.reverse() >>> print(ml) ['t', '条', '线', '阅', '梯']

setsubclass.py

class Set(list): def __init__(self,value=[]): list.__init__([]) self.concat(value) def intersect(self,other): res=[] for x in other: res.append(x) return res def union(self,other): res=Set(self) res.concat(other) return res def concat(self,value): for x in value: if not x in self: self.append(x) def __and__(self,other):return self.intersect(other) def __or__(self,other):return self.union(other) def __repr__(self):return 'Set:'+list.__repr__(self)

在idle执行下面语句

>>> import os >>> os.chdir(r'E:\documents\F盘') >>> from setsubclass import * >>> s1=Set([1,3,5,7]) >>> s2=Set([1,2,5,6,8]) >>> s1;s2;len(s1) Set:[1, 3, 5, 7] Set:[1, 2, 5, 6, 8] 4 >>> s1.intersect(s2) [1, 2, 5, 6, 8] >>> s1.union(s2) Set:[1, 3, 5, 7, 2, 6, 8] >>> s1|s2;s1&s2 Set:[1, 3, 5, 7, 2, 6, 8] [1, 2, 5, 6, 8] >>> s1.reverse() >>> print(s1) Set:[7, 5, 3, 1]

2 END

本文首发微信公众号:梯阅线条

更多内容参考python知识分享或软件测试开发目录。

文章转载自梯阅线条,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

文章被以下合辑收录

评论