0% found this document useful (0 votes)
9 views

17 Object Class

Uploaded by

saturnusfaunus54
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

17 Object Class

Uploaded by

saturnusfaunus54
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Object: Class, Attribute, Method

講師:林志偉
Class
- Build your own data type (1/2)

l Enhance to use magic method to initiate instance with


l Build a data type (class) to store poker card
parameters
# suit = 0梅花 1鑽⽯ 2紅⼼ 3⿊桃 # suit = 0梅花 1鑽⽯ 2紅⼼ 3⿊桃
# rank = 0-A 1-2 2-3 ... 9-10 10-J 11-Q 12-K # rank = 0-A 1-2 2-3 ... 9-10 10-J 11-Q 12-K
# build Card data type (class), which has two properties class Card:
class Card: def __init__(self, s, r):
suit = 0 self.suit = s
rank = 0 self.rank = r
# initiate card1 as 梅花A # initiate card3 as 紅⼼Q
card1 = Card() # initiate an instance, named card1 card3 = Card(2,11) # initiate an instance
card1.suit = 0 # assign value to instance's property card4 = Card(0, 12)
card1.rank = 0
print(type(card1)) l __init__(), is a Python Magic method, which is the
method starting and ending with double underscores
# initiate card2 as ⿊桃K '__'.
card2 = Card()
card2.suit = 3 l They are used in classes for different purpose
card2.rank = 12
Class
- Build your own data type (2/2)

l Enhance to print card by print()


l Print card
# suit = 0梅花 1鑽⽯ 2紅⼼ 3⿊桃 # suit = 0梅花 1鑽⽯ 2紅⼼ 3⿊桃
# rank = 0-A 1-2 2-3 ... 9-10 10-J 11-Q 12-K # rank = 0-A 1-2 2-3 ... 9-10 10-J 11-Q 12-K

class Card: class Card:


SUITS = ['♣', '♦', '♥', '♠'] SUITS = ['♣', '♦', '♥', '♠']
RANKS = ['A', '2', '3', '4', '5', '6',\ RANKS = ['A', '2', '3', '4', '5', '6',\
'7', '8', '9', '10', 'J', 'Q', 'K'] '7', '8', '9', '10', 'J', 'Q', 'K']

def __init__(self, s, r): def __init__(self, s, r):


self.suit = s self.suit = s
self.rank = r self.rank = r

def show(self): def __repr__(self):


print(self.SUITS[self.suit] + self.RANKS[self.rank]) return self.SUITS[self.suit] + self.RANKS[self.rank]

# initiate card3 as 紅⼼Q card3 = Card(2,11)


card3 = Card(2,11) # initiate an instance print(card3)
card3.show() card4 = Card(0,12)
print(card3) # a little bit strange print(card4)
建構 Class & 實例化 Object
class Circle: class Rectangle:
def __init__(self): def __init__(self, length, width):
self.radius = 0 self.length = length
self.width = width
def change_radius(self, radius):
self.radius = radius def set_length(self, length):
self.length = length
def get_radius (self):
return self.radius def set_width(self, width):
self.width = width
# main program
one_circle = Circle() # main program
another_circle = Circle() a_rectangle = Rectangle(2, 4)
one_circle.change_radius(4) b_rectangle = Rectangle(2) # error
print(one_circle.get_radius())
print(another_circle.get_radius())
Class Stack
class Stack: # main program
pancakes = Stack()
def __init__(self): pancakes.add_one('blueberry')
self.stack = [] pancakes.add_many('chocolate', 4)
print(pancakes.size())
def add_one(self, item): pancakes.remove_one()
self.stack.append(item) print(pancakes.size())
pancakes.prettyprint()
def add_many(self, item, n):
for i in range(n):
self.stack.append(item)

def remove_one(self):
self.stack.pop()

def remove_many(self, n):


for i in range(n):
self.stack.pop()

def size(self):
return len(self.stack)

def prettyprint(self):
for thing in self.stack[::-1]:
print('|_', thing, '_|')
Class Circle
# 建立 Class # main program
class Circle: a = Circle(10, 'red')
a.change_radius(20)
def __init__(self, radius, color): a.change_color('green')
self.radius = radius
self.color = color print(a.get_radius())
print(a.get_color())
def change_radius(self, radius): print(a.get_area())
self.radius = radius print(a.describe_circle())

def change_color(self, color): b = Circle(0.1, 'black')


self.color = color print(b.describe_circle())
print(b.get_area())
def get_radius(self):
return self.radius

def get_color(self):
return self.color

def get_area(self):
return (self.radius) **2 * 3.14

def describe_circle(self):
return f'It is a radius {self.radius} with {self.color} color'
#Lab

W3schools Exercises

需求: 在 w3schools.com中完成下列exercises
• classes
#Lab

建構 Class Rectangle
class Rectangle:
# main program
def __init__(self, width=1, length=1, line_color='white', body_color='white'):
self.width = width c = Rectangle(10, 'red') # bad assignment
self.length = length print('c:', c.describe())
self.line_color = line_color
self.body_color = body_color a = Rectangle(10, 20, 'red', 'pink')
self.line_width = 0.1 print('⻑⽅形 A: ', a.describe())
print('周⻑:', a.get_perimeter())
def change_size(self, width, legth):
pass b = Rectangle(1, 2, 'black', 'deep-blue')
print('⻑⽅形 B: ', b.describe())
def change_color(self, line_color, body_color): print('⼤⼩:', b.get_size())
pass

def get_size(self):
pass

def get_color(self):
pass

def get_area(self):
pass

def get_perimeter(self):
return 2 * (self.width + self.length)

def describe(self):
return f'這個⻑⽅形是 {self.width} * {self.length}. 線的顏⾊是{self.line_color}. 裡⾯顏⾊是{self.body_color}'
Backup
#Homework

Construct Queue class

需求:
請參考 Stack 的⽅式,撰寫程式來模擬佇列 (Queue 先進先出) ,意即先放入佇列的物件會先被取出
• 實作__init__⽅法
• 取得佇列的⻑度
• 新增⼀個物件到佇列
• 新增多個物件到佇列
• 從佇列裡移除⼀個物件
• 從佇列裡移除多個物件
• 顯⽰⽬前佇列的內容
• 實作程式並建立佇列物件,操作佇列驗證⽅法皆可正確執⾏
Object-Oriented Programming (OOP)
l 到⽬前為⽌,我們寫作的程式,都是寫⼀系列的 statement為主,加上 reusable 的函式,Python便會由上到下的執⾏
statement,這就是所謂的程序導向設計 (Procedure-Oriented Programming, POP)
l 雖然,Python的資料型別本⾝都是 object (像 str, int, float, list, set等),但由於我們在做程式設計時,並沒把物件 (Object) 當
成基本元件,融入我們設計程式的思考,所以在今天之前,基本上都是POP.
l 這種把物件 (Object) 當成基本元件,並在思考程式設計時,將物件建構跟使⽤納入其中,將object封裝進類別 (Class) ,以此
為主架構的就是物件導向設計 (Object-Oriented Programming, OOP)。
l OOP, 這個程式設計範式將「物件」作為程式的基本單元,將程式和資料封裝其中,以提⾼軟體的重⽤性、靈活性和擴充性
Object Consists of Properties and Methods
Class, Instance, Object
l Object (物件) 包含 properties
(attributes, 屬性) and methods
(⽅法),是某⼀個Class的實體存在
(instance), 是⼀個可操作的實體,
狀態會隨時改變,但架構與⾏為不
會改變,因其規範在Class內
l Class (類別) 可視為⼀個藍圖、⼀
個範本、⼀個可參考的文件,並沒
有實體存在
封裝 (Encapsulation)
使⽤類別的好處是可以將實作細節隱藏起來 (封裝),也不需詳細說明此類別的實作⽅式,只要告知提供
什麼功能,使⽤這個類別的⼈(程式設計師)完全不需知道實作細節,也不能擅⾃更動類別的設計。
這樣可以降低程式設計的複雜度,也能提⾼程式執⾏的穩定性

You might also like