编程实现Person类的封装,特征有:姓名和年龄,要求提供打印所有特征的行为。 编程实现Worker类的封装继承Person类,特征有:薪水。
时间: 2024-06-12 17:03:40 浏览: 87
JavaScript实现多态和继承的封装操作示例
```python
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def print_info(self):
print("姓名:{},年龄:{}".format(self.name, self.age))
class Worker(Person):
def __init__(self, name, age, salary):
super().__init__(name, age)
self.salary = salary
def print_info(self):
super().print_info()
print("薪水:{}".format(self.salary))
```
使用示例:
```python
person1 = Person("张三", 20)
person1.print_info() # 输出:姓名:张三,年龄:20
worker1 = Worker("李四", 30, 5000)
worker1.print_info() # 输出:姓名:李四,年龄:30,薪水:5000
```
阅读全文