|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
>>> #__bool__():布尔测试 -> __len__()
>>> class D:
... def __bool__(self):
... print('bool')
... return True
...
>>> d = D()
>>> print(bool(d))
bool
True
>>> class D:
... def __init__(self, data):
... self.data = data
... def __len__(self):
... print('len')
... return len(self.data)
...
>>> d = D('fishc')
>>> print(bool(d))
len
True
>>> # True 长度非零则直接返回True
>>> d = D([])
>>> print(bool(d))
len
False
>>> #跟比较运算相关的魔法方法:P189 < <= > >= == !=
>>> 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)
False
>>> print(s1 > s2)
False
>>> print(s1 == s2)
True
>>> print(s1 != s2)
True
>>> #__eq__()只会拦截等值判断(==),返回长度比较结果,不会拦截不等值判断(!=),故不等于号两边比较的依然是字符串ASCII码是否相同
>>> print(s1 <= s2)
True
>>> print(s1 >= s2)
False
>>> #如果不想让某个魔法方法生效,可以直接将其赋值为None
>>> 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
... __ne__ = None
...
>>> s1 = S('FishC')
>>> s2 = S('fishc')
>>> try:
... s1 != s2
... except TypeError as e:
... print(e)
...
'NoneType' object is not callable
>>> #这种做法也适用与代偿实现,定义第一个魔法方法为None后可以使代偿不实现
>>> class C:
... def __init__(self, data):
... self.data = dat
... self.data = data
...
>>> 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
... __contains__ = None #__contains__ -> __iter__() + __next__() -> __getitem__()
...
>>> c = C([1, 2, 3, 4, 5])
>>> try:
... print(3 in c)
... except TypeError as e:
... print(e)
...
'C' object is not a container |
|