设计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面向对象程序。