考点:
- 类的定义
- 实例方法
- 属性封装
- 继承
题目描述: 编写一个Python类 Employee
,该类具有以下属性:name
(员工姓名),salary
(员工薪水)。提供一个方法 give_raise
,该方法接受一个参数,并将其加到员工的薪水之上。然后,创建一个 Manager
类,该类继承自 Employee
类,并添加一个额外的方法 give_bonus
,该方法接受一个参数(奖金数额),并将其加到经理的薪水之上。
作答区:
# 请在此处编写你的代码
答案
class Employee:
def __init__(self, name, salary):
self._name = name
self._salary = salary
def give_raise(self, amount):
self._salary += amount
@property
def salary(self):
return self._salary
@property
def name(self):
return self._name
class Manager(Employee):
def give_bonus(self, bonus):
self._salary += bonus
# 测试代码
emp = Employee('John Doe', 50000)
emp.give_raise(5000)
print(f"{emp.name}'s new salary: {emp.salary}")
www.nbyyrcw.com
www.nbcxrcw.com
www.sxxcrcw.com
www.sxzjrcw.com
www.hzqtrcw.com
mgr = Manager('Jane Smith', 60000)
mgr.give_bonus(10000)
print(f"{mgr.name}'s new salary with bonus: {mgr.salary}")