定义一个学生类,创建两个学生对象,实现二人对话。 姓名 说话 学号 学习 籍贯 体能 生日 唱歌
时间: 2024-03-15 16:47:43 浏览: 154
好的,这里是代码实现:
```python
# 定义学生类
class Student:
def __init__(self, name, id, hometown, birthday):
self.name = name
self.id = id
self.hometown = hometown
self.birthday = birthday
def study(self):
print("%s is studying now." % self.name)
def sing(self):
print("%s is singing now." % self.name)
def talk(self, message):
print("%s says: %s" % (self.name, message))
def exercise(self):
print("%s is exercising now." % self.name)
def introduce(self):
print("My name is %s, my student ID is %s, I am from %s, my birthday is %s." % (self.name, self.id, self.hometown, self.birthday))
# 创建两个学生对象
student1 = Student("Tom", "2018001", "Shanghai", "2000-01-01")
student2 = Student("Lucy", "2018002", "Beijing", "2001-02-02")
# 二人对话
student1.talk("Hi, Lucy, how are you?")
student2.talk("I'm fine, thank you. How about you?")
student1.talk("I'm good, thank you. Let's study together!")
student2.study()
student1.exercise()
student2.talk("Do you like singing?")
student1.sing()
# 二人介绍自己
student1.introduce()
student2.introduce()
```
输出结果如下:
```
Tom says: Hi, Lucy, how are you?
Lucy says: I'm fine, thank you. How about you?
Tom says: I'm good, thank you. Let's study together!
Lucy is studying now.
Tom is exercising now.
Lucy says: Do you like singing?
Tom is singing now.
My name is Tom, my student ID is 2018001, I am from Shanghai, my birthday is 2000-01-01.
My name is Lucy, my student ID is 2018002, I am from Beijing, my birthday is 2001-02-02.
```
这样就实现了两个学生对象之间的对话和介绍。
阅读全文