在此基础上创建几个新对象,写出主函数
时间: 2024-03-14 12:48:32 浏览: 77
好的,我会按照您的要求回答问题,并根据您的要求创建新对象和编写主函数。以下是创建新对象和主函数的示例代码:
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Student(Person):
def __init__(self, name, age, major):
super().__init__(name, age)
self.major = major
class Teacher(Person):
def __init__(self, name, age, subject):
super().__init__(name, age)
self.subject = subject
# 创建新对象
person1 = Person("Tom", 25)
student1 = Student("Jerry", 20, "Computer Science")
teacher1 = Teacher("John", 35, "Math")
# 主函数
def main():
print("Person: {} is {} years old.".format(person1.name, person1.age))
print("Student: {} is {} years old and majoring in {}.".format(student1.name, student1.age, student1.major))
print("Teacher: {} is {} years old and teaches {}.".format(teacher1.name, teacher1.age, teacher1.subject))
if __name__ == "__main__":
main()
```
在上面的代码中,我们定义了三个类:Person、Student和Teacher。其中,Student和Teacher是继承自Person的子类。我们创建了三个新对象:person1、student1和teacher1,并在主函数中打印了它们的属性。最后,我们通过`if __name__ == "__main__":` 来保证主函数只有在被直接调用时才会执行。
阅读全文