开始使用免费开始使用

在类定义中使用属性

在上一个练习中,您定义了一个带有两个属性和两个用于设置这些属性的方法的 Employee 类。这类方法恰好被称为「setter」方法,但它绝不是唯一的方式。方法本质上是函数,因此函数能做的事,方法也都能做。比如,您可以用方法来打印、返回值、绘图、抛出异常——只要这些行为符合该类所描述对象的特性(例如,Employee 大概不会有 pivot_table() 方法)。

在本练习中,您将超越 setter 方法,学习如何利用已有的类属性来定义新方法。上个练习中的 Employee 类和 emp 对象已提供在您的脚本面板中。

本练习是课程的一部分

Python 面向对象编程

查看课程

交互式实操练习

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

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

    def set_salary(self, new_salary):
        self.salary = new_salary 
  
emp = Employee()
emp.set_name('Korel Rossi')
emp.set_salary(50000)

# Print the salary attribute of emp
____

# Increase salary of emp by 1500
emp.salary = ____ + ____

# Print the salary attribute of emp again
____
编辑并运行代码