#根据模拟list类的定义,分析类中的内置方法,实质还是调用对象中的方法
class list1():
def __init__(self): #构造函数,构造一个list是该函数自动调用,初始化
pass
def __del__(self): #析构函数,当用del函数产出list对象时,该函数会自动调用,删除对象
pass
def __len__(self): #长度,当用len(list1object)时,该函数会自动调用,返回对象长度
return 100
def __bool__(self): #bool函数,当用bool(self)时,该函数会自动调用,会自动判定True还是False,并购返回
return True
#而对于自定义的类,不能直接使用len(object)、bool(object),因为无法判断
#此使可以自定义这些函数,以实现相关功能
class Student():
def __len__(self): #若不定义__len__,则len(Student())会报错
return False #只能返回int 或True/False
def __bool__(self):
return True
print(bool(Student()))
print(len(Student())) #输出0
class Student1():
def __len__(self):
print('len methond is called')
return 5 #只能返回int
# def __bool__(self):
# return True
#如果没有__bool__,会自动调用__len__函数
print(bool(Student1())) #True 因为长度为8
class Student2():
pass
print(bool(Student2())) #没定义len,bool默认为true