Python中面向对象编程(OOP)基础实例
在Python中,面向对象编程(OOP)主要通过定义类和创建对象来实现。以下是一些基础实例:
- 定义一个类
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 创建对象
person1 = Person("Alice", 25)
- 继承父类
class Student(Person):
def study(self):
print(f"{self.name} is studying.")
# 创建子类对象
student = Student("Bob", 18))
student.study() # 输出:Bob is studying.
- 封装数据
class BankAccount:
def __init__(self, account_number, balance=0):
self.account_number = account_number
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient balance.")
else:
self.balance -= amount
# 创建账户实例
account = BankAccount(123456)
account.deposit(1000) # 存款1000元
print(account.balance) # 输出:11000
account.withdraw(5000) # 提取5000元
print(account.balance) # 输出:6000(余额)
# 账户余额在指定范围内的方法示例:
def check_balance_range(account, min_amount, max_amount):
current_balance = account.balance
if min_amount <= current_balance <= max_amount:
return f"Balance is within the range: {min_amount} - {max_amount}."
else:
return f"Balance is out of the range: {min_amount} - {max_amount}."
# 测试余额是否在指定范围内的方法
print(check_balance_range(account, 5000, 7000)), "示例输出:")
以上实例展示了Python中面向对象编程的基本概念,包括定义类、创建子类、封装数据以及使用方法检查余额等。
还没有评论,来说两句吧...