|
发表于 2023-8-17 17:21:59
|
显示全部楼层
## __contains\_\_(self, item)
用于实现成员关系的检测,对应的运算符是in 和 not in
```python
class C:
def __init__(self, data):
self.data = data
def __contains__(self, item):
print("嗨~")
return item in self.data
c = C([1, 2, 3, 4, 5])
3 in c
嗨~
True
6 in c
嗨~
False
```
### 代偿
Python在找不到`__iter__()`和`__next__()`魔法方法的情况下就会去查找`__getitem__()`方法
如果说没有实现`__contains__()`,但又使用了in和not in,namepython就会去查找`__iter__()`和`__next__()`魔法方法
```python
class C:
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]
self.i += 1
return item
c = C([1, 2, 3, 4, 5])
3 in c
```
只要return和要找的值一样就结束了
如果没有`__iter__()`和`__next__()`,会去找`__getitem__()`的魔法方法
```python
class C:
def __init__(self, data):
self.data = data
def __getitem__(self, index):
print("Getitem", end = ' -> ')
return self.data[index]
c = C([1, 2, 3, 4, 5])
3 in c
Getitem -> Getitem -> Getitem -> True
6 in c
Getitem -> Getitem -> Getitem -> Getitem -> Getitem -> Getitem -> False
```
## __bool\_\_()
```python
class D:
def __bool__(self):
print("Bool")
return True
d = D()
bool(d)
Bool
True
```
代偿,如果没有定义`__bool__()`魔法方法,那么Python就会去找找是否存在`__len__()`这个魔法方法,返回值非零则是True
```python
class D:
def __init__(self, data):
self.data = data
def __len__(self):
print("Len")
return len(self.data)
d = D("Solo")
bool(d)
Len
True
bool(d)
Len
False
```
## 比较运算
1. < `__lt__(self, other)`
2. <= `__le__(self, other)`
3. \> `__gt__(self, other)`
4. \>= `__ge__(self, other)`
5. == `__eq__(self, other)`
6. != `__ne__(self, other)`
字符串默认比较编码值大小,修改为比较长度
```python
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)
__le__ = None
__ge__ = None
s1 = S("Solo")
s2 = S("solo")
s1 < s2
False
s1 > s2
False
s1 == s2
True
s1 != s2 ##没有定义!=方法
True
s1 <= s2
Traceback (most recent call last):
File "<pyshell#235>", line 1, in <module>
s1 <= s2
TypeError: 'NoneType' object is not callable
```
|
|