Python

Class

Class 是什麼?

假設你今天在 Python 裡面要寫一個遊戲,

遊戲裡面有很多角色,

每個角色都有等級、血量、攻擊力等資料。

 

有什麼方法,可以讓我們寫起來輕鬆一點嗎?

Class 是什麼?

可以把 class 想成一個餅乾模型,你就可以用那個模型製作很多餅乾,每個餅乾都具有某些屬性。

一個餅乾稱之為一個「物件」(Object)  

Class 是什麼?

例子:

Class 

角色模板

屬性 1: 名稱

屬性 2: 血量

屬性 3: 等級

名稱= 忍者

血量=100

等級=5

名稱= 超人

血量=90

等級=10

名稱= 玩家

血量=20

等級=1

Object 

Object 

Object 

Class 怎麼寫: 宣告一個 class

class character ():
  
	def __init__(self, name, blood, level):
      
    	self.name = name
        self.blood = blood
        self.level = level

class 的名稱

initialize (=初始化)

宣告一個物件時自動執行這個函式

初始化一個 object 時需要輸入的內容

Class 怎麼寫: self 是啥

class character ():
  
	def __init__(self, name, blood, level):
      
    	self.name = name
        self.blood = blood
        self.level = level

self 基本上是「自己」的概念

self.name 的意思就是「自己的名字」

至於「自己」是誰,取決於你現在在處理哪個物件

因此在宣告 class 時習慣把「自己」統稱取作 self

*補充:其實可以把所有的 self 替換成任何字詞,例如 this, apple, hello 什麼都可以,但慣例使用 self

Class 怎麼寫: 宣告一個 Object

class character ():
  
	def __init__(self, name, blood, level):
      
    	self.name = name
        self.blood = blood
        self.level = level
        
        
 ninja = character (ninja, 100, 5)
 player = character (player, 20, 1)

宣告 objects

name

blood

level

Class 怎麼寫: 使用 Object

print (ninja.blood) #可以 print 輸出不同屬性
player.level += 1 #可以更改屬性的內容

Class 更多功能 - 方法 (methods)

class character ():
  
	def __init__(self, name, blood, level):
      
    	self.name = name
        self.blood = blood
        self.level = level
        
    def level_up (self, level):
      	self.level += 1
        
    def add_blood (self, blood):
      	self.blood += 20

ninja = character(ninja, 20, 1)
        
ninja.add_blood()
print(ninja.blood) # 會輸出 21

instance method

(實體方法)

用來對物件做事

函數第一個吃的一定是 self

Class 更多功能 - 方法 (methods)

class Character( ):
    count = 0   

    def __init__(self, name, level):
        self.name = name
        self.level = level
        Character.count += 1


class Ninja(Character):  
    def __init__(self, name, level, weapon):
      
        super().__init__(name, level)
        self.weapon = weapon

    

class method

(類別方法)

用來對 這「整個類別」做事

函數第一個吃的一定是 cls

(cls 就是 class )

Class 更多功能 - 繼承 

class Character( ):
    count = 0   

    def __init__(self, name, level):
        self.name = name
        self.level = level
        Character.count += 1


class Ninja(Character):  
    def __init__(self, name, level, weapon):
      
        super().__init__(name, level)
        self.weapon = weapon

    

用 super ( ) 就可以使子類別 Ninja 繼承父類別 Character的東西 

OOP (Object Oriented Programming) 物件導向程式設計

  • 以一個一個「物件」為主體寫程式 
  • OOP 算是一種寫程式的邏輯 / 方法
  • class 和 object 就屬於實踐 OOP

OOP 的特色及好處:

封裝

Encapsulation

繼承性

Inheritance

多型

Polymorphism

OOP (Object Oriented Programming) 物件導向程式設計

  1. 封裝:把東西包在 class 裡面,可以讓使用者忽略細節,並有一些方法能讓使用者較難直接獲取特定資訊(有興趣可以查 getter/setter)

2.  繼承:就剛剛講的繼承

3. 多型:可以用繼承的方法,創造多個子類別,讓每個子類別有一些不同的特色

 

Python: class

By Suzy Huang

Python: class

  • 166