開始使用免費開始

在類別定義中使用屬性

在上一個練習中,你定義了一個具有兩個屬性與兩個用來設定這些屬性的方式(methods)的 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
____
編輯並執行程式碼