定义学生和老师两个类,给学生类老师类添加属性和方法,并分别给学生类和老师类实例化两个对象
时间: 2024-05-08 09:18:17 浏览: 53
请看下面的例子-C++类和对象.
好的,这是一个编程问题,我可以回答。下面是定义学生和老师两个类,并添加属性和方法的代码:
```python
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade
def study(self):
print(f"{self.name} is studying hard to get a good grade.")
class Teacher:
def __init__(self, name, age, subject):
self.name = name
self.age = age
self.subject = subject
def teach(self):
print(f"{self.name} is teaching {self.subject} to the students.")
```
接下来是实例化两个学生对象和两个老师对象的代码:
```python
student1 = Student("Alice", 16, 10)
student2 = Student("Bob", 15, 9)
teacher1 = Teacher("Mr. Smith", 35, "Math")
teacher2 = Teacher("Ms. Johnson", 40, "English")
```
其中,student1和student2分别代表两个学生对象,他们的属性分别是"name": "Alice", "age": 16, "grade": 10和"name": "Bob", "age": 15, "grade": 9;teacher1和teacher2分别代表两个老师对象,他们的属性分别是"name": "Mr. Smith", "age": 35, "subject": "Math"和"name": "Ms. Johnson", "age": 40, "subject": "English"。并且,每个对象都有一个特定的方法,即学生对象的study()方法和老师对象的teach()方法。
阅读全文