Python中面向对象编程(OOP)基础实例

原创 迈不过友情╰ 2025-01-17 13:15 78阅读 0赞

在Python中,面向对象编程(OOP)主要通过定义类和创建对象来实现。以下是一些基础实例:

  1. 定义一个类
  1. class Person:
  2. def __init__(self, name, age):
  3. self.name = name
  4. self.age = age
  5. # 创建对象
  6. person1 = Person("Alice", 25)
  1. 继承父类
  1. class Student(Person):
  2. def study(self):
  3. print(f"{self.name} is studying.")
  4. # 创建子类对象
  5. student = Student("Bob", 18))
  6. student.study() # 输出:Bob is studying.
  1. 封装数据
  1. class BankAccount:
  2. def __init__(self, account_number, balance=0):
  3. self.account_number = account_number
  4. self.balance = balance
  5. def deposit(self, amount):
  6. self.balance += amount
  7. def withdraw(self, amount):
  8. if amount > self.balance:
  9. print("Insufficient balance.")
  10. else:
  11. self.balance -= amount
  12. # 创建账户实例
  13. account = BankAccount(123456)
  14. account.deposit(1000) # 存款1000元
  15. print(account.balance) # 输出:11000
  16. account.withdraw(5000) # 提取5000元
  17. print(account.balance) # 输出:6000(余额)
  18. # 账户余额在指定范围内的方法示例:
  19. def check_balance_range(account, min_amount, max_amount):
  20. current_balance = account.balance
  21. if min_amount <= current_balance <= max_amount:
  22. return f"Balance is within the range: {min_amount} - {max_amount}."
  23. else:
  24. return f"Balance is out of the range: {min_amount} - {max_amount}."
  25. # 测试余额是否在指定范围内的方法
  26. print(check_balance_range(account, 5000, 7000)), "示例输出:")

以上实例展示了Python中面向对象编程的基本概念,包括定义类、创建子类、封装数据以及使用方法检查余额等。

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

发表评论

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

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

相关阅读