在廖雪峰网站上获取对象信息章看到len()函数等价于__len__()方法,并且在我们自己定义的类里面,可以通过自己定义__len__()方法,然后通过len()函数来调用,有点疑惑,因此做一点小测试。
class MyDog(object):
def __len__(self):
return 100
dog = MyDog()
print(len(dog))
输出结果为100
疑问:是否任意字段都可以如此等价?将len改为saber试试,
class MyDog(object):
def __saber__(self):
return 100
dog = MyDog()
print(saber(dog))
结果异常,
F:\pROGramming\pYthon\python.exe C:/Users/boTTle/PycharmProjects/Ironac/test.py
Traceback (most recent call last):
File "C:/Users/boTTle/PycharmProjects/Ironac/test.py", line 6, in <module>
print(saber(dog))
NameError: name 'saber' is not defined
Process finished with exit code 1
故此猜想,应该是内建函数len()的逻辑就是调用str方法str.__len__(),而在用户自定义__len__()之后,原方法逻辑被替换,但len()逻辑不变,因此可以如此等价替换,且仅限于该关键字。