class Person:
"""
比较运算符号
其中python 可以更具eq推导出 ne
et推导出gt
ge推导出le
bool
迭代器:
必须实现 def __iter__(self): 和 def __next__(self):
1、迭代器的使用是先返回一个迭代器 即是调用 __iter__ 方法
2、 然后是调用 __next__ 依次返回一个内容
"""
def __init__(self,a,b):
self.a = a
self.b=b
def __eq__(self, other): # ==
return self.a==other.a
# def __ne__(self, other):
# return self.a != other.a
def __ge__(self, other): #> =
return self.a >= other.a
def __le__(self, other): # >=
return self.a <= other.a
def __lt__(self, other): # <
return self.a < other.a
def __gt__(self, other): # >
return self.a > other.a
def __bool__(self):
return self.a>5
def __getitem__(self, item): #迭代器 1
self.b+=1
if self.b>=10:
raise StopIteration
return self.b
def __iter__(self): #迭代器 1
print("iter")
# return iter((1,2,3,4)) #返回一个迭代器对象
self.b = 4 #每次调用迭代器时初始化方法
return self # 返回self 必须实现 def __next__(self): 方法
def __next__(self):
print("next")
self.b += 1
if self.b >= 10:
raise StopIteration
return self.b
p = Person(2,4)
print(p)
p1=Person(6,4)
print(p==p1)
print(p>p1)
print("!= ------>",p!=p1)
if p1:
print("xxxx")
print("---------------")
for i in p:
print(i)
print("b==",p.b)
print(".............")
for i in p:
print(i)
print("---------------")
import collections
print(isinstance(p,collections.Iterator)) # 判断是否是一个迭代器
结果:
<__main__.Person object at 0x0280F710>
False
False
!= ------> True
xxxx
---------------
iter
next
5
next
6
next
7
next
8
next
9
next
b== 10
.............
iter
next
5
next
6
next
7
next
8
next
9
next
---------------
True