定义父类 Father, 有age,name 属性,定义speak(方法 打印 介绍信息。定义2个子类,boy和gril两个子类,分别实现重写speak0方
时间: 2023-05-22 11:05:51 浏览: 153
法,输出自己的介绍信息。
以下是代码示例:
```python
class Father:
def __init__(self, age, name):
self.age = age
self.name = name
def speak(self):
print("Hello, my name is", self.name, "and I am", self.age, "years old.")
class Boy(Father):
def speak(self):
print("Hi, I am a boy. My name is", self.name, "and I am", self.age, "years old.")
class Girl(Father):
def speak(self):
print("Hi, I am a girl. My name is", self.name, "and I am", self.age, "years old.")
# 测试
father = Father(50, "John")
father.speak()
boy = Boy(10, "Tom")
boy.speak()
girl = Girl(8, "Lily")
girl.speak()
```
输出结果如下:
```
Hello, my name is John and I am 50 years old.
Hi, I am a boy. My name is Tom and I am 10 years old.
Hi, I am a girl. My name is Lily and I am 8 years old.
```
阅读全文