开始使用免费开始使用

扩展类

在上一个练习中,您定义了一个包含两个属性和两个用于设置这些属性的方法的 Employee 类。请记住,方法本质上是函数,因此函数能做的事,方法也都可以。

例如,只要行为适合该类的对象,您就可以使用方法来打印或返回数值,甚至绘图。比如,Employee 大概就不应该有一个 pivot_table() 方法。

在本练习中,您将学习如何利用已有的类属性来定义新方法。上一个练习中的 Employee 类和 emp 对象已在您的 script.py 中。

本练习是课程的一部分

Python 面向对象编程入门

查看课程

练习说明

  • Employee 类中添加一个方法 give_raise(),使其将工资增加 give_raise() 接收的 amount 参数值。
  • 创建 emp 对象。
  • 打印 empsalary 属性。
  • emp 对象上调用 give_raise(),将其工资增加 1500

交互式实操练习

通过完成这段示例代码来试试这个练习。

class Employee:
  def set_name(self, new_name):
    self.name = new_name

  def set_salary(self, new_salary):
    self.salary = new_salary 

  # Add a give_raise() method with amount as an argument
  ____ ____(____, ____):
    ____.____ = ____.____ + ____

# Create the emp object
emp = ____
emp.set_name('Korel Rossi')
emp.set_salary(50000)

# Print the salary
print(____.____)

# Give emp a raise of 1500
____.____(____)
print(emp.salary)
编辑并运行代码