添加类构造函数
在本练习中,您将继续完善 Employee 类。不再使用上一课中编写的 set_salary() 等方法,而是引入一个构造函数,在对象创建时就为员工设置姓名和薪资。
在构造函数中初始化属性是个好主意,因为这可以确保对象在创建的那一刻就具备所有必要的属性。
本练习是课程的一部分
Python 面向对象编程入门
交互式实操练习
通过完成这段示例代码来试试这个练习。
class Employee:
# Create __init__() method
____ ____(____, name, ____):
# Create the name and salary attributes
self.____ = ____
____ = ____
def give_raise(self, amount):
self.salary += amount
def monthly_salary(self):
return self.salary / 12
emp = Employee("Korel Rossi")
print(emp.name)
print(emp.salary)