Python面向对象编程:实例解析

原创 悠悠 2025-01-20 18:33 73阅读 0赞

面向对象编程(Object-Oriented Programming,OOP)是程序设计的一种范式。在Python中,OOP的主要特性包括:

  1. 封装(Encapsulation)

    • 将数据和操作数据的方法绑定在一起。
    • 只能通过特定的接口访问数据。

    ```python
    class BankAccount:

    1. def __init__(self, account_number):
    2. self.account_number = account_number
    3. self.balance = 0
    4. # 调用方法,实现封装
    5. def deposit(self, amount):
    6. if amount > 0:
    7. self.balance += amount
    8. else:
    9. print("Deposit amount must be positive.")
    10. def withdraw(self, amount):
    11. if amount > 0 and self.balance >= amount:
    12. self.balance -= amount
    13. else:
    14. print("Withdrawal amount must be positive and within balance.")
  1. 继承(Inheritance)

    • 允许一个类(子类)继承另一个类(父类)的属性和方法。

    ```python
    class Animal:

    1. def __init__(self, name):
    2. self.name = name
    3. # 父类通用方法
    4. def speak(self):
    5. return "The animal speaks."

    class Dog(Animal): # 子类继承父类

    1. def speak(self):
    2. return super().speak() + " Woof!"
  1. 多态(Polymorphism)

    • 即同一接口可以有不同的实现方式,使代码更加灵活。
    1. class Shape:
    2. def area(self):
    3. pass # 假设每个形状都有area方法
    4. class Circle(Shape):
    5. def area(self):
    6. return math.pi * (self.radius ** 2))
    7. class Rectangle(Shape):
    8. def area(self):
    9. return self.width * self.height
    10. shape1 = Circle(radius=5)
    11. shape2 = Rectangle(width=10, height=5))
    12. print(shape1.area()) # 输出:78.539816339745
    13. print(shape2.area()) # 输出:50

以上就是Python面向对象编程中的实例解析,通过创建类和实例化,实现了数据的封装、继承以及多态等特性。

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

发表评论

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

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

相关阅读