My blogs

The greatest test of courage on earth is to bear defeat without losing heart.

0%

OOP

介紹

物件導向程式設計(Object-oriented programming,簡稱OOP),它是一個具有物件(Object)概念的開發方式,能夠提高軟體的重用性、擴充性及維護性。


物件中包含

  • 類別(Class)
  • 物件(Object)
  • 屬性(Attribute)
  • 建構式(Constructor)
  • 方法(Method)

Creating Class and Object

建立classclassname :

建立物件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:

# class attribute
species = "bird"

# instance attribute
# 初始化
def __init__(self, name, age):
self.name = name #名稱屬性
self.age = age #年齡屬性


# obj = class()

# instantiate the animal class
blu = animal("Blu", 10)
woo = animal("Woo", 15)

# access the class attributes
print(f"Blu is a {blu.__class__.species}")
print(f"Woo is also a {woo.__class__.species}")

# __class__.species. 類的所有實例的類屬性都相同

# access the instance attributes
print(f"{blu.name} is {blu.age} years old")
print(f"{woo.name} is {woo.age} years old")

# isinstance
print(isinstance(blu, animal)) # 執行結果:True

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:

# instance attributes
def __init__(self, name, age):
self.name = name
self.age = age

# instance method
def sing(self, song):
return f"{self.name} sings {song}"

def dance(self):
return f"{self.name} is now dancing"


# instantiate the object
blu = animal("Blu", 10)

# call our instance methods
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")

# child class


class dog(dogfather):

def __init__(self):

# call super() function
# 繼承
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):
# private obj
self.__maxprice = 900

def sell(self):
print(f"Selling Price: {self.__maxprice}")

def setMaxPrice(self, price):
self.__maxprice = price


c = Price()
c.sell()

# change the price
c.__maxprice = 1000
c.sell()

# using setter function
c.setMaxPrice(1000)
c.sell()



ps:private 物件 無法直接修改數值。


  • 結果如下 :

Selling Price: 900
Selling Price: 900
Selling Price: 1000


參考網站


如果您喜歡我的文章,請幫我按五下 ,感謝大家。