版权所有,未经许可,禁止转载
章节
Python 介绍
Python 开发环境搭建
Python 语法
Python 变量
Python 数值类型
Python 类型转换
Python 字符串(String)
Python 运算符
Python 列表(list)
Python 元组(Tuple)
Python 集合(Set)
Python 字典(Dictionary)
Python If … Else
Python While 循环
Python For 循环
Python 函数
Python Lambda
Python 类与对象
Python 继承
Python 迭代器(Iterator)
Python 模块
Python 日期(Datetime)
Python JSON
Python 正则表达式(RegEx)
Python PIP包管理器
Python 异常处理(Try…Except)
Python 打开文件(File Open)
Python 读文件
Python 写文件
Python 删除文件与文件夹
Python 继承
继承允许我们在定义一个类时,让该类继承另一个类的所有方法和属性。
父类是被继承的类,也称为基类。
子类是继承父类的类,也称为派生类。
创建父类
任何类都可以是父类,创建父类的语法和创建普通类是一样的:
示例
创建一个名为Person
的类,包含属性:firstname
,lastname
, 方法:printname
:
class Person:
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
# 使用Person类创建对象,然后执行printname方法:
x = Person("Kevin", "Wu")
x.printname()
创建子类
要创建子类,需将父类作为参数传入:
示例
创建一个名为Student
的类,它将继承Person类的属性和方法:
class Student(Person):
pass
注意: 当您不想给类添加任何属性或方法时,使用pass关键字。
现在Student
类具有与Person
类相同的属性和方法。
示例
使用Student
类创建对象,然后执行printname
方法:
x = Student("Kevin", "Tony")
x.printname()
添加init()函数
到目前为止,我们已经创建了一个子类,它继承了父类的属性和方法。
现在将__init__()
函数添加到子类(不再使用pass
关键字)。
注意: 每当创建新对象时,都会自动调用类的
__init__()
函数。
示例
将__init__()
函数添加到Student
类:
class Student(Person):
def __init__(self, fname, lname):
# 添加属性
当您添加了__init__()
函数后,子类将不再继承父类的__init__()
函数。
注意: 子函数的
__init__()
重写父函数的__init__()
。
要保留父类的__init__()
函数的功能,可在子类的__init__()
函数中调用父类的__init__()
函数:
示例
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
现在,我们已经给子类添加了__init__()
函数,并调用了父类的__init__()
函数,下面我们将在__init__()
函数中添加其他功能。
添加属性
示例
在Student
类中添加一个关于毕业年份的属性:
class Student(Person):
def __init__(self, fname, lname):
Person.__init__(self, fname, lname)
self.graduationyear = 2019
2019年应该是一个变量,并在创建学生对象时传递给Student类。为此,在__init__()
函数中添加另一个year
参数:
示例
添加一个year
参数,创建对象时传入毕业年份:
class Student(Person):
def __init__(self, fname, lname, year):
Person.__init__(self, fname, lname)
self.graduationyear = year
x = Student("Kevin", "Tony", 2019)
加入方法
示例
在Student
类中添加一个名为welcome
的方法:
class Student(Person):
def __init__(self, fname, lname, year):
Person.__init__(self, fname, lname)
self.graduationyear = year
def welcome(self):
print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
如果在子类中添加父类中的同名方法,则父类的方法将被重写。