设计时间类Time和日期类Date,Birthtime类由Time类和Date类派生,并且增加一个数据成员Childname用于表示小孩的姓名,编写程序输出小孩的姓名和出生时间。
时间: 2024-03-22 21:40:23 浏览: 60
下面是时间类Time的实现:
```python
class Time:
def __init__(self, hour=0, minute=0, second=0):
self.hour = hour
self.minute = minute
self.second = second
def __str__(self):
return "{:02d}:{:02d}:{:02d}".format(self.hour, self.minute, self.second)
```
下面是日期类Date的实现:
```python
class Date:
def __init__(self, year=0, month=0, day=0):
self.year = year
self.month = month
self.day = day
def __str__(self):
return "{:04d}-{:02d}-{:02d}".format(self.year, self.month, self.day)
```
下面是Birthtime类的实现:
```python
class Birthtime(Time, Date):
def __init__(self, child_name, year, month, day, hour=0, minute=0, second=0):
Time.__init__(self, hour, minute, second)
Date.__init__(self, year, month, day)
self.child_name = child_name
def __str__(self):
return "{} was born on {} at {}".format(self.child_name, Date.__str__(self), Time.__str__(self))
```
现在可以测试一下Birthtime类的功能:
```python
birth_time = Birthtime("Alice", 2021, 8, 1, 10, 30, 0)
print(birth_time)
```
输出结果为:
```
Alice was born on 2021-08-01 at 10:30:00
```
这个例子展示了如何使用继承来创建新的类,并且如何在子类中调用父类的构造函数。
阅读全文