__super__()
- 在 Python 中,super 是一个内置函数,用于调用父类方法。
- 该函数可以在子类中调用父类中被重写的方法,从而实现对父类方法的继承并且进行扩展。它能够动态地查找当前子类继承链中的下一个类,从而允许设计者更加灵活地组织代码。
- 简单案例
简单案例
class FATHER:def status(self):print('FATHER is in status zero')class SON(FATHER):def status(self):super().status()print('SON is in status zero')s = SON()
s.status()
FATHER is in status zero
SON is in status zero
>>>
调用与重写
class FATHER:def __init__(self,name):self.name = namedef status1(self):print("{} is in status1...".format(self.name))class SON(FATHER):def __init__(self,name,arg1):super().__init__(name)self.arg1 = arg1def status1(self):super().status1()print("{} is in status1 with args {} ".format(self.name,self.arg1))d = SON("SOMEWHERE", "CQ:UNKNOWN")
d.status1()
SOMEWHERE is in status1...
SOMEWHERE is in status1 with args CQ:UNKNOWN
__repr__
- repr函数是一个内置函数,用于将对象转换为供解释器读取的形式。通常情况下,repr函数返回的字符串应该是一个可以用来重新创建该对象的字符串表达式。
简单示例
class Person:def __init__(self, name, age):self.name = nameself.age = agedef __repr__(self):return f"Person name={self.name}, age={self.age}"p = Person("River Chandler", 20)
print(repr(p))
Person name=River Chandler, age=20
容器类
- 容器类是指可以包含其他对象的类,例如列表、元组、字典等
- 容器案例
class MyList:#初始化def __init__(self, *args):self.data = list(args)#返回列表的长度def __len__(self):return len(self.data)#按下标访问元素的功能def __getitem__(self, index):return self.data[index]#设置元素def __setitem__(self, index, value):self.data[index] = value#删除元素def __delitem__(self, index):del self.data[index]#迭代列表def __iter__(self):return iter(self.data)#判断元素是否存在def __contains__(self, value):return value in self.datamylist = MyList(1,2,3,4)
#类型
print(type(mylist))#长度
print(len(mylist)) #索引
print(mylist[0]) #设置
mylist[0] = 0
print(mylist[0]) #删除
del mylist[0]
print(len(mylist))#迭代
for item in mylist:print(item) #判断存在
print(2 in mylist)
print(0 in mylist)
<class '__main__.MyList'>
4
1
0
3
2
3
4
True
False
call函数
- call触发案例
class FATHER:def __init__(self,name):self.name = namedef __call__(self,msg):print('{}CLASS in STATUS: {}'.format(self.name,msg))a = FATHER("HARRY")
a("STATUS ONE")
HARRYCLASS in STATUS: STATUS ONE
>>>
issubclass
- 用于判断第一个参数是否是第二个参数的子类
class FATHER:passclass SON(FATHER):passprint(issubclass(SON,FATHER))
__del__
- 简单案例
class FATHER:def __init__(self,name):self.name = namedef __del__(self):try:print("del "+str(self.name))except:print("del "+"no attribute self.name")a = FATHER("a")
b = FATHER("b")
del a.name
del a
del b
del no attribute self.name
del b
>>>
__enter__和__exit__
- with as语句块
- 执行with as语句时,__enter__函数会被调用
- 执行with as语句完毕以后,__exit__函数会被调用
class MyClass:def __enter__(self):print("__enter__ is called!")def __exit__(self,type,value,trace):print("__exit__ is called!")M = MyClass()
with M as m:pass
__enter__ is called!
__exit__ is called!
>>>
组合
-
在一个类中以另外一个类的对象作为数据属性
-
其实区别也不太,很符合直觉地
class People():school = 'SH'def __init__(self,name,age,gender):self.name = nameself.age = ageself.gender = genderclass Teacher(People):def __init__(self,name,age,gender):super().__init__(name,age,gender)print("Teacher is built")class Course():def __init__(self,name,credit,semester):self.name = nameself.credit = creditself.semester = semesterelectrodynamics = Course('electrodynamics',4,"2SPR")
Theoretical_Mechanics = Course('Theoretical_Mechanics',3,"2SPR")class Student(People):def __init__(self,name,age,gender,course=None):if course is None:self.course = []else:self.course = [course]super().__init__(name,age,gender)def choose_course(self,course):self.course.append(course) def report_course(self):for Course in self.course:print(Course.name,end="; ")HARRY = Student("HARRY",20,"MALE",Theoretical_Mechanics)
HARRY.choose_course(electrodynamics)
HARRY.report_course()
POTTER = Teacher("POTTER",40,"FEMALE")
Theoretical_Mechanics; electrodynamics; Teacher is built
>>>