Python继承是什么及怎么实现

其他教程   发布日期:2025年04月13日   浏览次数:81

这篇文章主要介绍“Python继承是什么及怎么实现”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Python继承是什么及怎么实现”文章能帮助大家解决问题。

Python 继承

继承允许我们定义继承另一个类的所有方法和属性的类。

父类是继承的类,也称为基类。

子类是从另一个类继承的类,也称为派生类。

创建父类

任何类都可以是父类,因此语法与创建任何其他类相同:

实例

创建一个名为 Person 的类,其中包含 firstname 和 lastname 属性以及 printname 方法:

  1. class Person:
  2. def __init__(self, fname, lname):
  3. self.firstname = fname
  4. self.lastname = lname
  5. # Python学习交流裙:279199867
  6. def printname(self):
  7. print(self.firstname, self.lastname)
  8. # 使用 Person 来创建对象,然后执行 printname 方法:
  9. x = Person("Bill", "Gates")
  10. x.printname()

运行实例

  1. python_inheritance_parent.py
  2. Bill Gates

创建子类

要创建从其他类继承功能的类,请在创建子类时将父类作为参数发送:

实例

创建一个名为 Student 的类,它将从 Person 类继承属性和方法:

  1. class Student(Person):
  2. pass

注释:如果您不想向该类添加任何其他属性或方法,请使用 pass 关键字。

现在,Student 类拥有与 Person 类相同的属性和方法。

实例

使用 Student 类创建一个对象,然后执行 printname 方法:

  1. x = Student("Elon", "Musk")
  2. x.printname()

运行实例

  1. python_inheritance_child.py
  2. Elon Musk

添加 init() 函数

到目前为止,我们已经创建了一个子类,它继承了父类的属性和方法。

我们想要把 init() 函数添加到子类(而不是 pass 关键字)。

注释:每次使用类创建新对象时,都会自动调用 init() 函数。

实例

为 Student 类添加 init() 函数:

  1. class Student(Person):
  2. def __init__(self, fname, lname):
  3. # 添加属性等

当您添加 init() 函数时,子类将不再继承父的 init() 函数。

注释:子的 init() 函数会覆盖对父的 init() 函数的继承。

如需保持父的 init() 函数的继承,请添加对父的 init() 函数的调用:

实例

  1. class Student(Person):
  2. def __init__(self, fname, lname):
  3. Person.__init__(self, fname, lname)

运行实例

  1. python_inheritance_init.py
  2. Elon Musk

现在,我们已经成功添加了 init() 函数,并保留了父类的继承,我们准备好在 init() 函数中添加功能了。

使用 super() 函数

Python 还有一个 super() 函数,它会使子类从其父继承所有方法和属性:

实例

  1. class Student(Person):
  2. def __init__(self, fname, lname):
  3. super().__init__(fname, lname)

运行实例

  1. python_inheritance_super.py
  2. Elon Musk

通过使用 super() 函数,您不必使用父元素的名称,它将自动从其父元素继承方法和属性。

添加属性

实例

把名为 graduationyear 的属性添加到 Student 类:

  1. class Student(Person):
  2. def __init__(self, fname, lname):
  3. super().__init__(fname, lname)
  4. self.graduationyear = 2019

运行实例

  1. python_inheritance_add_prop_1.py
  2. 2019

在这例子中,2019 年应该是一个变量,并在创建 student 对象时传递到 Student 类。为此,请在 init() 函数中添加另一个参数:

实例

添加 year 参数,并在创建对象时传递正确的年份:

  1. class Student(Person):
  2. def __init__(self, fname, lname, year):
  3. super().__init__(fname, lname)
  4. self.graduationyear = year
  5. x = Student("Elon", "Musk", 2019)

运行实例

  1. python_inheritance_add_prop_2.py
  2. 2019

添加方法

实例

把名为 welcome 的方法添加到 Student 类:

  1. class Student(Person):
  2. def __init__(self, fname, lname, year):
  3. super().__init__(fname, lname)
  4. self.graduationyear = year
  5. def welcome(self):
  6. print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)

运行实例

  1. python_inheritance_add_method.py
  2. Welcome Elon Musk to the class of 2019

提示:如果您在子类中添加一个与父类中的函数同名的方法,则将覆盖父方法的继承。

以上就是Python继承是什么及怎么实现的详细内容,更多关于Python继承是什么及怎么实现的资料请关注九品源码其它相关文章!