## class - 可以想成是一堆variables以及functions的集合。利用class來寫程式,可以從原本的函式導向轉換為物件導向,就能更容易維持某些共同特性,讓程式更有條理,在許多地方非常常用。 - 在程式中,可能存在許多 Object (物件),底下可能包括基本資訊,以及可能的操作。 - 若存在許多相似Object,就可以一一建立class,將他們分類,直接從上層的統一規範。 - 作法 - 產生class ```python class <className>: ``` - 建立時初始設定variables (self) ```python def __init__(self, <parameters>): ... ``` - 加入functions ```python def <method>(): ... ``` - 建立class後,產生底下object,並存取/呼叫 ```python <variableName> = <className>() # 給定初始值 # 但不含self參數 <object>.<attribute> # 存取屬性 <object>.<method>() # 執行方法 ``` - 具體實例 ```python class Animal(): def __init__(self, species, name, age): self.species = None self.name = name self.age = age def action(self): if self.species == 'cat': print("Meow~~~") elif self.species == 'dog': print("Woof~~~") elif self.species == 'bird': print("Chu~~~") else: print("~~~~~") pet = Animal('cat', 'Poppy', 3) pet.action() # output: Meow~~~ ```
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up