Python中面向对象编程(OOP)的基本原则示例?
在Python中,面向对象编程(OOP)的基本原则包括封装、继承和多态。
- 封装(Encapsulation):
这是OOP的核心。将数据和操作数据的方法组合在一起,形成一个“黑箱”,外部只能通过定义的接口进行操作。
class BankAccount:
def __init__(self, initial_amount):
self.balance = initial_amount
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
raise ValueError("Insufficient balance.")
self.balance -= amount
- 继承(Inheritance):
子类可以继承父类的属性和方法,从而减少代码重复。
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclass must implement abstract method.")
class Dog(Animal):
def speak(self):
return "Woof!"
animal = Animal("Generic animal"))
dog = Dog("Fido")
print(animal.name) # Generic animal
print(dog.speak()) # Woof!
- 多态(Polymorphism):
同一个方法名,可以在不同的类中有不同的实现方式。
在上述代码中,speak
方法是多态的一个例子。 Dog 类的 speak
方法与 Animal 类的 speak
方法不同,实现了代码的复用和灵活性。
还没有评论,来说两句吧...