.创建一个“Student”子类,增加属性“ID”,增加方法: (1)查询时间:定义query_time函数,调用后可以在命令行显示当前的时间 (2)写入文档:定义write函数函数,调用时需提供一个文档路径,从命令行输入一串话,可以将该内容保存到指定文档路径 (3)摇色子(3个):定义函数throw_dice(),调用后会生成三个数(范围在1-6之内的整数)显示运行效果
时间: 2024-02-07 09:03:57 浏览: 62
好的,下面是Python代码实现:
```python
import random
import time
class Student(Person):
def __init__(self, name, age, home, ID):
super().__init__(name, age, home)
self.ID = ID
def query_time(self):
print("Current time is: " + time.strftime("%H:%M:%S", time.localtime()))
def write(self, file_path):
content = input("Please enter the content you want to write: ")
with open(file_path, "w") as f:
f.write(content)
def throw_dice(self):
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
dice3 = random.randint(1, 6)
print(f"The result of throwing dice: {dice1}, {dice2}, {dice3}")
```
这个代码定义了一个名为Student的子类,继承了Person类,并增加了一个ID属性。它还具有三个方法:query_time, write和throw_dice。query_time方法将打印出当前时间,write方法将从命令行输入一串话并将其写入指定的文档路径,throw_dice方法将生成三个1到6之间的随机整数并打印出来。现在,我们可以创建一个Student对象,并调用其方法,如下所示:
```python
student = Student("Tom", 25, "London", "123456")
student.introduceMyself()
student.query_time()
student.write("test.txt")
student.throw_dice()
```
这将输出以下内容(其中throw_dice方法的输出可能不同):
```
Hello, my name is Tom, I am 25 years old and I come from London.
Current time is: 10:23:45
Please enter the content you want to write: Hello world!
The result of throwing dice: 2, 6, 3
```
阅读全文