类的继承与方法重载
1 继承的特点
减少代码并且灵活的定制新类,子类可以继承父类的属性和方法,但另一方面子类无法继承父类的私有属性和私有方法,子类可以修改父类的方法,也可以定义新的方法。
2 继承的语法定义
方式:在类名之后添加(继承的父类)
多重继承时,括号中放入多个父类名
示例:class myclass(baseclass)
重载父类方法时,只需要在子类中定义与父类同名的方法
class
Person:
def
__init__(self,name=
'Bob'
,age=
20
,sex=
1
):
self.name=name
self.age=age
self.sex=sex
def
printInfo(self):
print
(
"Person class:name:"
+self.name+
" age:"
+str(self.age)+
" sex:"
+str(self.sex))
class
Student(Person):
def
learn(self):
print
(
"Student class:learning..."
)
class
collegeStudent(Student):
def
printInfo(self):
print
(
"collegeStudent class:college student information..."
)
def
learn(self):
print
(
"collegeStudent class:add the transaction before calling the super method..."
)
super().learn()
print
(
"collegeStudent class:add the transaction after calling the super method..."
)
if
__name__ ==
'__main__'
:
stu=Student()
stu.printInfo()
stu.learn()
col=collegeStudent()
col.printInfo()
col.learn()
多重继承时,采用广度优先搜索,优先继承最先继承的父类的方法
class
A():
def
fun(self):
print
(
"A fun..."
)
class
B():
def
fun(self):
print
(
"B fun..."
)
class
C(A,B):
pass
class
D(B,A):
pass
C().fun()
D().fun()