在 Python 中,继承是面向对象编程的一个重要特性,它允许我们创建一个新类,该类是现有类的扩展。继承可以提高代码的重用性和可维护性。下面是一个继承和子类的示例,其中我们从 Person 类派生出一个 Student 类。
Person
Student
首先,我们定义一个 Person 类,该类包含一些基本属性和方法:
class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): print(f"Hello, my name is {self.name} and I am {self.age} years old.") def __str__(self): return f"Person(name={self.name}, age={self.age})"
在这个类中:
__init__
greet
__str__
接下来,我们定义一个 Student 类,该类继承自 Person 类,并添加了新的属性和方法:
class Student(Person): def __init__(self, name, age, student_id, major): super().__init__(name, age) self.student_id = student_id self.major = major def study(self): print(f"{self.name} is studying {self.major}.") def __str__(self): return f"Student(name={self.name}, age={self.age}, student_id={self.student_id}, major={self.major})"
super()
student_id
major
study
我们现在可以创建 Person 和 Student 对象,并调用它们的方法:
# 创建 Person 对象 person = Person("Alice", 30) print(person) person.greet() # 创建 Student 对象 student = Student("Bob", 20, "S12345", "Computer Science") print(student) student.greet() student.study()
运行上述代码的输出将是:
Person(name=Alice, age=30) Hello, my name is Alice and I am 30 years old. Student(name=Bob, age=20, student_id=S12345, major=Computer Science) Hello, my name is Bob and I am 20 years old. Bob is studying Computer Science.
子类可以重写父类的方法,以提供特定于子类的实现。以下是一个示例,其中 Student 类重写了 greet 方法:
class Student(Person): def __init__(self, name, age, student_id, major): super().__init__(name, age) self.student_id = student_id self.major = major def greet(self): print(f"Hi, I'm {self.name}, a {self.age}-year-old student majoring in {self.major}.") def study(self): print(f"{self.name} is studying {self.major}.") def __str__(self): return f"Student(name={self.name}, age={self.age}, student_id={self.student_id}, major={self.major})"
现在,当我们调用 Student 对象的 greet 方法时,将使用 Student 类中的实现:
# 创建 Student 对象 student = Student("Bob", 20, "S12345", "Computer Science") student.greet() # 输出: Hi, I'm Bob, a 20-year-old student majoring in Computer Science.
通过继承,我们可以创建一个新类,该类是现有类的扩展。子类继承父类的属性和方法,并且可以添加新的属性和方法或重写父类的方法。通过继承和方法重写,可以实现多态性,提高代码的重用性和可维护性。上述示例展示了如何从 Person 类派生出 Student 类,并使用继承和方法重写来扩展类的功能。
原文链接:codingdict.net