创建一个 Person 类(父类),通过扩展创建 Student 和 Teacher 类(子类);并在主类 TestOne 里实现创建对象,成员变量的初始化、 方法调用等;
时间: 2023-05-26 12:04:30 浏览: 86
```
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print("My name is {} and I'm {} years old.".format(self.name, self.age))
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def introduce(self):
super().introduce()
print("I am a student with ID: {}.".format(self.student_id))
class Teacher(Person):
def __init__(self, name, age, subject):
super().__init__(name, age)
self.subject = subject
def introduce(self):
super().introduce()
print("I am a teacher of {}.".format(self.subject))
# TestOne
student = Student("Tom", 18, "12345")
teacher = Teacher("John", 35, "Mathematics")
student.introduce()
teacher.introduce()
```
输出结果:
```
My name is Tom and I'm 18 years old.
I am a student with ID: 12345.
My name is John and I'm 35 years old.
I am a teacher of Mathematics.
```
阅读全文