設計Python面向對象編程(OOP)時,需要遵循一些基本原則和最佳實踐。以下是一些關鍵步驟和建議:
__
)前綴來表示私有屬性,如__name
。_
)前綴表示受保護的屬性,如_name
;使用無特殊符號的屬性和方法表示公有的。@property
裝飾器來創建屬性的getter方法,使用@<attribute>.setter
裝飾器來創建屬性的setter方法。class Person:
def __init__(self, name, age):
self.__name = name # 私有屬性
self._age = age # 受保護的屬性
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
if isinstance(value, str):
self.__name = value
else:
raise ValueError("Name must be a string")
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if isinstance(value, int) and value >= 0:
self._age = value
else:
raise ValueError("Age must be a non-negative integer")
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def study(self):
print(f"{self.name} is studying.")
class Teacher(Person):
def teach(self):
print(f"{self.name} is teaching.")
abc
模塊定義抽象基類,子類必須實現抽象方法。from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
class Person:
def __init__(self, name, age):
self.__name = name # 私有屬性
self._age = age # 受保護的屬性
@property
def name(self):
return self.__name
@name.setter
def name(self, value):
if isinstance(value, str):
self.__name = value
else:
raise ValueError("Name must be a string")
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if isinstance(value, int) and value >= 0:
self._age = value
else:
raise ValueError("Age must be a non-negative integer")
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def study(self):
print(f"{self.name} is studying.")
class Teacher(Person):
def teach(self):
print(f"{self.name} is teaching.")
# 使用示例
dog = Dog("Buddy", 3, "12345")
print(dog.speak()) # 輸出: Woof!
cat = Cat("Whiskers", 2, "67890")
print(cat.speak()) # 輸出: Meow!
student = Student("Alice", 18, "S12345")
student.study() # 輸出: Alice is studying.
teacher = Teacher("Mr. Smith", 45, "T67890")
teacher.teach() # 輸出: Mr. Smith is teaching.
通過遵循這些原則和最佳實踐,可以設計出結構清晰、易于維護和擴展的Python面向對象程序。