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("Bill", "Gates")
x.printname()
  • 创建子类
    要创建从其他类继承功能的类,请在创建子类时将父类作为参数发送:
    实例
    创建一个名为 Student 的类,它将从 Person 类继承属性和方法:
class Student(Person):
  pass
  • 添加 init() 函数
    到目前为止,我们已经创建了一个子类,它继承了父类的属性和方法。
    我们想要把 init() 函数添加到子类(而不是 pass 关键字)。
    注释:每次使用类创建新对象时,都会自动调用 init() 函数。
    实例
    为 Student 类添加 init() 函数:
class Student(Person):
  def __init__(self, fname, lname):
    # 添加属性等

当您添加 init() 函数时,子类将不再继承父的 init() 函数。
注释:子的 init() 函数会覆盖对父的 init() 函数的继承。
如需保持父的 init() 函数的继承,请添加对父的 init() 函数的调用:

class Student(Person):
  def __init__(self, fname, lname):
    Person.__init__(self, fname, lname)
  • 使用 super() 函数
    Python 还有一个 super() 函数,它会使子类从其父继承所有方法和属性:
class Student(Person):
  def __init__(self, fname, lname):
    super().__init__(fname, lname)

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

class Student(Person):
  def __init__(self, fname, lname, year):
    super().__init__(fname, lname)
    self.graduationyear = year

  def welcome(self):
    print("Welcome", self.firstname, self.lastname, "to the class of", self.graduationyear)
posted @ 2021-11-19 10:49  Ada_CN  阅读(87)  评论(0编辑  收藏  举报