Python中面向对象编程(OOP)的基本原则示例?

原创 古城微笑少年丶 2025-02-23 06:00 7阅读 0赞

在Python中,面向对象编程(OOP)的基本原则包括封装、继承和多态。

  1. 封装(Encapsulation):
    这是OOP的核心。将数据和操作数据的方法组合在一起,形成一个“黑箱”,外部只能通过定义的接口进行操作。
  1. class BankAccount:
  2. def __init__(self, initial_amount):
  3. self.balance = initial_amount
  4. def deposit(self, amount):
  5. self.balance += amount
  6. def withdraw(self, amount):
  7. if amount > self.balance:
  8. raise ValueError("Insufficient balance.")
  9. self.balance -= amount
  1. 继承(Inheritance):
    子类可以继承父类的属性和方法,从而减少代码重复。
  1. class Animal:
  2. def __init__(self, name):
  3. self.name = name
  4. def speak(self):
  5. raise NotImplementedError("Subclass must implement abstract method.")
  6. class Dog(Animal):
  7. def speak(self):
  8. return "Woof!"
  9. animal = Animal("Generic animal"))
  10. dog = Dog("Fido")
  11. print(animal.name) # Generic animal
  12. print(dog.speak()) # Woof!
  1. 多态(Polymorphism):
    同一个方法名,可以在不同的类中有不同的实现方式。

在上述代码中,speak 方法是多态的一个例子。 Dog 类的 speak 方法与 Animal 类的 speak 方法不同,实现了代码的复用和灵活性。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,7人围观)

还没有评论,来说两句吧...

相关阅读