python类的特殊方法(二)

bool

使用 bool(myobject) 的背后是调用我们定义的 myobject.__bool__()的结果。如果未定义 bool,则会尝试调用len()的结果,如果返回0,则bool(myobject)` 的结果为 False,反之为 True。

contains(self, item)

这个特殊方法不会直接调用, 而是在使用 in 操作时调用

class test(object):
    b='ddd'

    def __contains__(self, item):
        if item in self.b:
            return True
        else:
            return False


m = test()
m.b = 'few'
print('d' in m)

因为我们更改了实例属性的值,所以返回值是 False

如果删去 __contains__方法:

class test(object):
    b='ddd'


m = test()
print('d' in m)

将出现错误:

Traceback (most recent call last):
  File "I:/Program Code/Python/testing/mydict.py", line 18, in <module>
    print('d' in m)
TypeError: argument of type 'test' is not iterable

由此我们也可以看出,可迭代类型均支持 in 操作,自定义类必须定义 __contains__后才支持。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容