代偿
# !/usr/bin/python3# -*- coding: utf-8 -*-
# @Time : 2023/2/21 21:14
# @Author : xiongming
# @File : daichang.py
# @Desc : 代偿
# 成员关系的检测
class C:
def __init__(self, data):
self.data = data
def __contains__(self, item):
print("contains判断了是否存在")
return item in self.data
c = C()
print(3 in c)
class D:
def __init__(self, data):
self.data = data
def __iter__(self):
print("Iter", end='->')
self.i = 0
return self
def __next__(self):
print("Next", end='->')
if self.i == len(self.data):
raise StopIteration
item = self.data
self.i += 1
return item
d = D()
# 代偿,contains不存在,找iter、next代偿
print(3 in d)
class F:
def __init__(self, data):
self.data = data
def __getitem__(self, item):
print("Getitem", end=' ->')
return self.data
f = F()
# 查找三次找到 3
print(3 in f)
# 布尔bool
class Q:
def __bool__(self):
print("Bool")
return True
q = Q()
print(bool(q))
print("-----------------")
class E:
def __init__(self, data):
self.data = data
def __len__(self):
print("Len")
return len(self.data)
e = E("FishC")
print(bool(e))
print("-----------------")
# 比较运算
class S(str):
def __lt__(self, other):
return len(self) < len(other)
def __gt__(self, other):
return len(self) > len(other)
def __eq__(self, other):
return len(self) == len(other)
s1 = S("FishC")
s2 = S("fishc")
# 判断长度
print(s1 < s2)
print(s1 > s2)
print(s1 == s2)
# 走得父类字符串比较编码值大小
print(s1 != s2)
页:
[1]