Python 面向对象编程示例:创建 Person、Student 和 Teacher 类
class Person: def init(self, name, age): self.name = name self.age = age
def say_hello(self):
print(f'Hello, my name is {self.name} and I am {self.age} years old.')
class Student(Person): def init(self, name, age, grade): super().init(name, age) self.grade = grade
def say_hello(self):
super().say_hello()
print(f'I am a student in grade {self.grade}.')
class Teacher(Person): def init(self, name, age, subject): super().init(name, age) self.subject = subject
def say_hello(self):
super().say_hello()
print(f'I am a teacher of {self.subject}.')
person1 = Person('John', 25) person1.say_hello()
student1 = Student('Jane', 16, 11) student1.say_hello()
teacher1 = Teacher('Mr. Smith', 40, 'math') teacher1.say_hello()
原文地址: https://www.cveoy.top/t/topic/nP1n 著作权归作者所有。请勿转载和采集!