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. 小强的HTML5移动开发之路(8)——坦克大战游戏2

    来自:http://blog.csdn.net/cai_xingyun/article/details/48629015 在上一篇文章中我们已经画出了自己的坦克,并且可以控制自己的坦克移动,我们继续接 ...

  2. LCS问题(最长公共子序列)-动态规划实现

    问题描述: 问题] 求两字符序列的最长公共字符子序列 注意: 并不要求子串(字符串一)的字符必须连续出现在字符串二中. 思路分析: 最优子结构和重叠子问题的性质都具有,所以要采取动态规划的算法 最长公 ...

  3. H5学习之旅-H5的布局(10)

    两种实现方式:div和table div实现布局的方式 代码实例 <!DOCTYPE html> <html lang="en"> <head> ...

  4. hadoop环境配置过程中可能遇到问题的解决方案

    Failed to set setXIncludeAware(true) for parser 遇到此问题一般是jar包冲突的问题.一种情况是我们向java的lib目录添加我们自己的jar包导致had ...

  5. 配置hadoop-1.2.1 eclipse开发环境

    写这篇文章的目的是记录解决配置过程中的问题 首先我们先看下这篇博文 配置hadoop-1.2.1 eclipse开发环境 但是在[修改 Hadoop 源码]这里,作者发布的 hadoop-core-1 ...

  6. Linux System Programming --Chapter Eight

    内存管理 一.分配动态内存的几个函数 用户空间内存分配:malloc.calloc.realloc1.malloc原型如下:extern void *malloc(unsigned int num_b ...

  7. 一个小公式帮你轻松将IP地址从10进制转到2进制

    网络工程师经常会遇到的一个职业问题:如何分配IP,通过子网如何捕捉某一网段或某台机器?他们甚至能够进行精准的分析和复杂的开发......凡此种种,其实与一些他们头脑中根深蒂固的常识性理论存有某种内在的 ...

  8. ubuntu中taglist和ctags安装使用

    1.使用命令安装ctags: 2.安装taglist 下载: http://vim.sourceforge.net/scripts/download_script.php?src_id=6416 拷贝 ...

  9. Java-transient总结

    纸上得来终觉浅,绝知此事要躬行  --陆游    问渠那得清如许,为有源头活水来  --朱熹 transient有"临时的","短暂的"含义,我们了解过Seri ...

  10. 网站开发进阶(二十一)Angular项目信息错位显示问题解决

    Angular项目信息错位显示问题解决 绪 最近在项目开发过程中遇到这样一个棘手的问题:查询出所有订单信息后,点击选择某一个订单,查询出的结果是上一次查询所得的结果.而且会出现点击两次才可以显示订单详 ...