1、 注意,__len__(self) 方法一般与 len(对象) 方法搭配使用
2、 len(对象) 方法,用来求对象的某个属性(变量)的元素的个数,会自动调用对象的**__len__(self)**方法
3、再次强调,len(对象) 方法,是用来求对象的某个属性(变量)的元素的个数,会自动调用对象的__len__(self) 方法。而__len__(self) 方法恰恰是用来返回需要求的该属性的元素的个数。
# main.py
# 说明:函数 len(对象) 用来求对象的某个属性的元素的个数,会自动调用对象的__len__(self)方法,
class Test(object):
def __init__(self, arg_1):
self.arg_1 = arg_1
self.arg_2 = [1, 2, 3, 4]
def __len__(self):
return len(self.arg_2)
if __name__ == '__main__':
pass
pass
test = Test('Hello, word')
print(len(test)) # 函数 len(对象) 用来求对象的某个属性的元素的个数,会自动调用对象的__len__(self)方法,
# 使用 len(对象) 方法时,如果对象中没有实现 __len__(self) 方法,就会报类型错误。
结果:4



