Python中面向对象编程(OOP)的基本实践

原创 ╰半橙微兮° 2025-01-03 11:18 67阅读 0赞

在Python中,面向对象编程(OOP)是一种编写程序的方式,它将数据和操作数据的方法绑定在一起。以下是OOP在Python中的基本实践:

  1. 创建类:使用class关键字定义一个类。例如:
  1. class Dog:
  2. def __init__(self, name):
  3. self.name = name
  4. def bark(self):
  5. return f"{self.name} says Woof!"
  1. 实例化对象:通过类名调用方法来创建对象。例如:
  1. my_dog = Dog("Rex")
  1. 继承:子类可以继承父类的属性和方法。例如:
  1. class MediumDog(Dog):
  2. def __init__(self, name, breed="Poodle"):
  3. super().__init__(name)
  4. self.breed = breed
  5. my_medium_dog = MediumDog("Fido", breed="Shiba Inu")
  1. 封装:通过设置访问权限(如公有属性和私有方法)来保护对象的数据。例如:
  1. class BankAccount:
  2. def __init__(self, account_number, balance=0):
  3. self.account_number = account_number
  4. self.balance = balance
  5. # 公有方法
  6. def deposit(self, amount):
  7. self.balance += amount
  8. return self.balance
  9. # 私有方法,外部无法访问
  10. def _transfer(self, amount, recipient_account):
  11. if amount <= 0:
  12. raise ValueError("Transfer amount must be positive.")
  13. # 确保转入账户有足够的余额
  14. if recipient_account.balance + amount < 0:
  15. raise InsufficientFundsError("Recipient account balance insufficient for transfer.")
  16. # 转账操作
  17. recipient_account.balance -= amount
  18. self.balance += amount
  19. @property
  20. def account_number(self):
  21. return self._account_number
  22. @account_number.setter
  23. def account_number(self, value):
  24. self._account_number = value

以上就是在Python中面向对象编程的基本实践。

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

发表评论

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

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

相关阅读