在第十六課中,我們將繼續深入探討物件導向程式設計 (OOP) 的進階主題,尤其是 Python 中的特殊方法、屬性和繼承的進階概念。
請新建一個檔案 oop_advanced.py
。
__init__
和 __str__
。它們有特定的用途,並且允許你定義物件的某些內建行為。pythonCopy code
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
def __str__(self):
return f"'{self.title}' by {self.author}"
def __len__(self):
return len(self.title) + len(self.author)
book = Book("1984", "George Orwell")
print(book) # 輸出: '1984' by George Orwell
print(len(book)) # 輸出: 數字 (書名和作者名稱的長度之和)
@property
裝飾器允許你在不調用函數的情況下獲取物件的某個值。pythonCopy code
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def diameter(self):
return self._radius * 2
circle = Circle(5)
print(circle.diameter) # 輸出: 10 (而不是 circle.diameter())
super()
): 當你在一個子類中想要調用其超類的初始化方法時,可以使用 super()
函數。pythonCopy code
class Animal:
def __init__(self, species):
self.species = species
class Dog(Animal):
def __init__(self, name):
super().__init__("Dog")
self.name = name
dog = Dog("Buddy")
print(dog.species) # 輸出: Dog
pythonCopy code
class Swimmer:
def swim(self):
print("I can swim!")
class Flyer:
def fly(self):
print("I can fly!")
class Duck(Swimmer, Flyer):
pass
duck = Duck()
duck.swim() # 輸出: I can swim!
duck.fly() # 輸出: I can fly!
請在 oop_advanced.py
中輸入並運行上述代碼片段。這些進階的 OOP 概念將為你在 Python 中的編程提供更多的靈活性和表達力