Python中面向对象编程(OOP)的基本实践
在Python中,面向对象编程(OOP)是一种编写程序的方式,它将数据和操作数据的方法绑定在一起。以下是OOP在Python中的基本实践:
- 创建类:使用
class
关键字定义一个类。例如:
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
return f"{self.name} says Woof!"
- 实例化对象:通过类名调用方法来创建对象。例如:
my_dog = Dog("Rex")
- 继承:子类可以继承父类的属性和方法。例如:
class MediumDog(Dog):
def __init__(self, name, breed="Poodle"):
super().__init__(name)
self.breed = breed
my_medium_dog = MediumDog("Fido", breed="Shiba Inu")
- 封装:通过设置访问权限(如公有属性和私有方法)来保护对象的数据。例如:
class BankAccount:
def __init__(self, account_number, balance=0):
self.account_number = account_number
self.balance = balance
# 公有方法
def deposit(self, amount):
self.balance += amount
return self.balance
# 私有方法,外部无法访问
def _transfer(self, amount, recipient_account):
if amount <= 0:
raise ValueError("Transfer amount must be positive.")
# 确保转入账户有足够的余额
if recipient_account.balance + amount < 0:
raise InsufficientFundsError("Recipient account balance insufficient for transfer.")
# 转账操作
recipient_account.balance -= amount
self.balance += amount
@property
def account_number(self):
return self._account_number
@account_number.setter
def account_number(self, value):
self._account_number = value
以上就是在Python中面向对象编程的基本实践。
还没有评论,来说两句吧...