class Set(object):
def __init__(self,data=None):
if data == None:
self.__data = []
else:
if not hasattr(data,'__iter__'):
#提供的数据不可以迭代,实例化失败
raise Exception('必须提供可迭代的数据类型')
temp = []
for item in data:
#集合中的元素必须是可哈希
hash(item)
if not item in temp:
temp.append(item)
self.__data = temp #析构函数
def __del__(self):
del self.__data #添加元素,要求元素必须可哈希
def add(self, other):
hash(other)
if other not in self.__data:
self.__data.append(other)
else:
print('元素已存在,操作被忽略') #删除元素
def remove(self,other):
if other in self.__data:
self.__data.remove(other)
print('删除成功')
else:
print('元素不存在,删除操作被忽略') #随机弹出并返回一个元素
def pop(self):
if not self.__dat:
print('集合已空,弹出操作被忽略')
return
import random
item = random.choice(self.__data)
self.__data.remove(item)
return item #运算符重载,集合差集运算
def __sub__(self, other):
if not isinstance(other,Set):
raise Exception('类型错误')
#空集合
result = Set()
#如果一个元素属于当前集合而不属于另一个集合,添加
for item in self.__data:
if item not in other.__data:
result.__data.append(item)
return result #提供方法,集合差集运算,复用上面的代码
def difference(self,other):
return self - other #|运算符重载,集合并集运算
def __or__(self, other):
if not isinstance(other,Set):
raise Exception('类型错误')
result = Set(self.__data)
for item in other.__data:
if item not in result.__data:
result.__data.append(item)
return result #提供方法,集合并集运算
def union(self,otherSet):
return self | otherSet #&运算符重载,集合交集运算
def __and__(self, other):
if not isinstance(other,Set):
raise Exception('类型错误')
result = Set()
for item in self.__data:
if item in other.__data:
result.__data.append(item)
return result #^运算符重载,集合对称差集
def __xor__(self, other):
return (self-other) | (other-self) #提供方法,集合对称差集运算
def symetric_difference(self,other):
return self ^ other #==运算符重载,判断两个集合是否相等
def __eq__(self, other):
if not isinstance(other,Set):
raise Exception('类型错误')
if sorted(self.__data) == sorted(other.__data):
return True
return False #>运算符重载,集合包含关系
def __gt__(self, other):
if not isinstance(other,Set):
raise Exception('类型错误')
if self != other:
flag1 = True
for item in self.__data:
if item not in other.__data:
#当前集合中有的元素不属于另一个集合
flag1 = False
break
flag2 = True
for item in other.__data:
if item not in self.__data:
#另一集合中的元素不属于当前集合
flag2 = False
break
if not flag1 and flag2:
return True
return False #>=运算符重载,集合包含关系
def __ge__(self, other):
if not isinstance(other,Set):
raise Exception('类型错误')
return self == other or self > other #提供方法,判断当前集合是否为另一个集合的真子集
def issubset(self,other):
return self<other #提供方法,判断当前集合是否为另一集合的超集
def issuperset(self,other):
return self > other #提供方法,清空集合所有元素
def clear(self):
while self.__data:
del self.__data[-1]
print('集合已清空') #运算符重载,使得集合可迭代
def __iter__(self):
return iter(self.__data) #运算符重载,支持in运算符
def __contains__(self, item):
return item in self.__data #支持内置函数len()
def __len__(self):
return len(self.__data) #直接查看该类对象时调用该函数
def __repr__(self):
return '{'+str(self.__data)[1:-1]+'}' #使用print()函数输出该类对象时调用该函数
__str__ = __repr__

Python_重写集合的更多相关文章

  1. python_重写数组

    class MyArray: '''All the elements in this array must be numbers''' def __IsNumber(self,n): if not i ...

  2. laravel 集合

    最近一直在用laravel框架,比较喜欢laravel的ORM(通常我们理解的Model)...但是默认情况下,Eloquent 查询的结果总是返回 Collection 实例...所有不得不了解co ...

  3. laravel集合

    1.简介 Illuminate\Support\Collection 类为处理数组数据提供了平滑.方便的封装.例如,查看下面的代码,我们使用辅助函数 collect 创建一个新的集合实例,为每一个元素 ...

  4. 关于 laravel 集合的使用

    常用的有 count() count方法返回集合中所有项的数目: $collection = collect([1, 2, 3, 4]); $collection->count(); forPa ...

  5. Java依据集合元素的属性,集合相减

    两种方法:1.集合相减可以使用阿帕奇的一个ListUtils.subtract(list1,list2)方法,这种方法实现必须重写集合中对象的属性的hashCode和equals方法,集合相减判断的会 ...

  6. Map的内容按字母顺序排序

    map有自带的排序功能,但需要重写排序方法,代码如下: package coreJava.com.shindo.corejava.map; import java.util.ArrayList; im ...

  7. MongoDB如何释放空闲空间?

    当我们从MongoDB中删除文档或集合时,MongoDB并不会将已经占用了的磁盘空间释放,它会一直维护已经占用了磁盘空间的数据文件,尽管数据文件中可能存在大大小小的空记录列表(empty record ...

  8. struts2之OGNL用法

    浅析OGNL OGNL是Object-GraphNavigation Language的缩写,是一种功能强大的表达式语言 通过它简单一致的表达式语法,可以存取对象的任意属性,调用对象的方法,遍历整个对 ...

  9. PostFX v2后期处理特效包:升级更惊艳的视觉效果

    https://mp.weixin.qq.com/s/BMkLLuagbhRSWspzeGhK7g Post-Processing Stack后期处理特效包能够轻松创建和调整高质量视觉效果,实现更为惊 ...

随机推荐

  1. 基于VB中WINSOCK控件的网上象棋系统的实现

    本文发表在<微型机与应用>杂志2001年第3期. 基于VB中WINSOCK控件的网上象棋系统的实现 马根峰1   ,  孙艳2  , 王平1 (1.重庆邮电学院自动化学院,重庆,40006 ...

  2. Android Support Design 控件 FloatingActionButton

    经常刚可以看到悬浮控件,比如印象笔记的下面那个绿色的悬浮按钮,这个控件非常简单也是来自Design Support Library中同理需要在android studio中加入依赖库:design库 ...

  3. Collections.sort()的分析

    首先我们得说明在Collections里面有两个排序方法 public static <T> void sort(List<T> list, Comparator<? s ...

  4. 【Visual C++】游戏编程学习笔记之一:五毛钱特效之透明和半透明处理

    本系列文章由@二货梦想家张程 所写,转载请注明出处. 本文章链接:http://blog.csdn.net/terence1212/article/details/44163799 作者:ZeeCod ...

  5. 手持机设备公司(WINCE/ANDROID/LINUX)

    1.深圳扬创科技有限公司网址: http://www.yctek.com/ 2.无锡盈达聚力科技有限公司 点击打开链接 3.上海鲲博通信技术有限公司(主要为用WINCE开发导航产品) 点击打开链接 4 ...

  6. 史上最全webview详解

    本文来自:http://www.jianshu.com/users/320f9e8f7fc9/latest_articles WebView在现在的项目中使用的频率应该还是非常高的. 我个人总觉得HT ...

  7. shell中关于sort的-o选项

    sort -o选项意思为将排序后的结果写入文件,但你可能会说我可以重定向啊: sort >file 但如果你要排序文件names里的行再写回排序后的结果: sort names > nam ...

  8. Mac环境svn的使用

    在Windows环境中,我们一般使用TortoiseSVN来搭建svn环境.在Mac环境下,由于Mac自带了svn的服务器端和客户端功能,所以我们可以在不装任何第三方软件的前提下使用svn功能,不过还 ...

  9. Jfinal调用Orcale存储过程

    因为项目需要,最近一直在学习Orcale存储过程,但发现在网上很少有人写Jave中Jfinal调用Orcale存储过程的文章,即使有也是几年前的,很多都不能用,今天给大家分享一段Jfinal调用Orc ...

  10. 2MySQL Server 系统架构

    2.2MySQL Server 系统架构 总的来说,MySQL 可以看成是二层架构,第一层我们通常叫做SQL Layer,在MySQL 数据库系统处理底层数据之前的所有工作都是在这一层完成的,包括权限 ...