鱼C论坛

 找回密码
 立即注册
查看: 996|回复: 0

[学习笔记] 类和对象-魔法方法-下

[复制链接]
发表于 2023-4-1 10:20:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

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
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-4-27 09:54

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表