資訊之芽北區py班
yjrubixcube
OOP stands for Object-Oriented Programming, which is a programming paradigm that focuses on creating objects that encapsulate data and behavior. In Python, OOP is implemented through classes and objects.
沒用繼承
用繼承
也可以用
Animal.__init__(self, name)
c = Cat("Hello Kitty", "vase")
d = Dog("狗勾", "啊啊啊")
c.reqires()
c.knock_over()
d.reqires()
d.make_sound()
# Hello Kitty reqires food and water
# Hello Kitty knocked over the vase
# 狗勾 reqires food and water
# 狗勾 says 啊啊啊
也可以一次繼承很多個 class
super()
是傳進去的第一個class
也可以繼承好幾層
練習
寫出兩個繼承Dog
的class Dachshund, PitBull
。
Dachshund
有額外的屬性length
PitBull
有額外的屬性strength
並建立以下兩個instance
type | name | sound | length | strength |
---|---|---|---|---|
Dachshund | Sausage | Woof! | 30 | x |
Pitbull | Bull | Woof! | x | 100 |
b = bird()
d = duck()
c = chicken()
say_something(b) # Moo!
say_something(d) # 西呱
say_something(c) # 嘰嘰喳喳
因為 bird, duck, chicken
都有 speak
方法
所以都可以在say_something
裡面呼叫.speak()
如果我的子class沒有.speak()
?
class Ditto(bird):
def __init__(self):
super().__init__()
cow = Ditto()
say_something(cow)
Moo!
用 bird
裡面的
練習
改寫上面的class,使得我們使用print(obj)
的時候會印出該obj對應的字串(Moo!, 西呱, 嘰嘰喳喳
)
hint: 可以試試看上節課講的Magic method?
前面雙底線代表 private attribute/method
只能在class裡面存取
b = Bank("合作金庫", 8787)
b.print_info()
# 合作金庫
# 8787
b.name += "台大分店"
b.print_info()
# 合作金庫台大分店
# 8787
b.__total += 10000
# AttributeError: 'Bank' object has no attribute '__total'
b.__total = 10000
b.print_info()
# 合作金庫台大分店
# 8787
如果我真的想改 private 怎麼辦
b.more_money(10000)
b.print_info()
# 合作金庫台大分店
# 18787
練習
請加強合作金庫的安保,讓外人也不能直接改name,只能透過obj.change_name(name)
來更改