介紹
物件導向程式設計(Object-oriented programming,簡稱OOP
),它是一個具有物件(Object)概念的開發方式,能夠提高軟體的重用性、擴充性及維護性。
物件中包含
- 類別(Class)
- 物件(Object)
- 屬性(Attribute)
- 建構式(Constructor)
- 方法(Method)
Creating Class and Object
建立class
classname :
建立物件obj = class()
Python 函式isinstance()
來判斷類別(Class)與物件(Object)的關係。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| class animal:
species = "bird"
def __init__(self, name, age): self.name = name self.age = age
blu = animal("Blu", 10) woo = animal("Woo", 15)
print(f"Blu is a {blu.__class__.species}") print(f"Woo is also a {woo.__class__.species}")
print(f"{blu.name} is {blu.age} years old") print(f"{woo.name} is {woo.age} years old")
print(isinstance(blu, animal))
|
ps:blu.__class__.species
取的class 建立attribute。
Blu is a bird
Woo is also a bird
Blu is 10 years old
Woo is 15 years old
True
方法(Method)
定義方法(Method)和函式(Function)的語法很像,都是 def
關鍵字開頭,接著自訂名稱。
至少要有一個self
參數。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class animal:
def __init__(self, name, age): self.name = name self.age = age
def sing(self, song): return f"{self.name} sings {song}"
def dance(self): return f"{self.name} is now dancing"
blu = animal("Blu", 10)
print(blu.sing("'Happy'")) print(blu.dance())
|
Blu sings ‘Happy’
Blu is now dancing
Inheritance
繼承是一種創建新類以使用現有類的細節而不修改它的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| class dogfather:
def __init__(self): print("dogfather is ready")
def whoisThis(self): print("dogfather")
def swim(self): print("dogfather faster")
class dog(dogfather):
def __init__(self):
super().__init__() print("dog is ready")
def whoisThis(self): print("dog")
def run(self): print("Run faster")
p1 = dog() p1.whoisThis() p1.swim() p1.run()
|
ps:super()
在__init__()
方法中使用了函數。
這允許我們__init__()
在子類中運行父類的方法。
dogfather is ready
dog is ready
dog
dogfather faster
Run faster
Encapsulation(private)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Price:
def __init__(self): self.__maxprice = 900
def sell(self): print(f"Selling Price: {self.__maxprice}")
def setMaxPrice(self, price): self.__maxprice = price
c = Price() c.sell()
c.__maxprice = 1000 c.sell()
c.setMaxPrice(1000) c.sell()
|
ps:private 物件 無法直接修改數值。
Selling Price: 900
Selling Price: 900
Selling Price: 1000
參考網站