設(shè)計(jì)Python面向?qū)ο缶幊蹋∣OP)時(shí),需要遵循一些基本原則和最佳實(shí)踐。以下是一些關(guān)鍵步驟和建議:
__
)前綴來(lái)表示私有屬性,如__name
。_
)前綴表示受保護(hù)的屬性,如_name
;使用無(wú)特殊符號(hào)的屬性和方法表示公有的。@property
裝飾器來(lái)創(chuàng)建屬性的getter方法,使用@<attribute>.setter
裝飾器來(lái)創(chuàng)建屬性的setter方法。class Person:
def __init__(self, name, age):
self.__name = name # 私有屬性
self._age = age # 受保護(hù)的屬性
@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
模塊定義抽象基類(lèi),子類(lèi)必須實(shí)現(xiàn)抽象方法。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 # 受保護(hù)的屬性
@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.
通過(guò)遵循這些原則和最佳實(shí)踐,可以設(shè)計(jì)出結(jié)構(gòu)清晰、易于維護(hù)和擴(kuò)展的Python面向?qū)ο蟪绦颉?/p>