创建一个带有私有属性的类:
定义一个 BankAccount 类,具有以下私有属性和方法:
属性:
__balance:初始值为 0
方法:
deposit:增加余额
withdraw:从余额中扣除,如果余额不足则打印 Insufficient funds
练习: 实例化 BankAccount 对象,执行存款和取款操作,并查看是否能直接访问私有余额。
python类与对象
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
1条回答 默认 最新
关注♥ 该回答引用于ChatGPT,如若有用,还请题主采纳!♥
在 Python 中,可以通过在属性名前加上两个下划线(
__)来定义私有属性。私有属性只能在类的内部访问,外部无法直接访问。下面是一个BankAccount类的示例,包含私有属性__balance和相应的方法deposit和withdraw。BankAccount 类的实现
class BankAccount: def __init__(self): self.__balance = 0 # 初始化私有属性 __balance def deposit(self, amount): """增加余额""" if amount > 0: self.__balance += amount print(f"成功存款: {amount}元,当前余额: {self.__balance}元") else: print("存款金额必须大于0") def withdraw(self, amount): """从余额中扣除,如果余额不足则打印 Insufficient funds""" if amount > self.__balance: print("Insufficient funds") elif amount <= 0: print("取款金额必须大于0") else: self.__balance -= amount print(f"成功取款: {amount}元,当前余额: {self.__balance}元") def get_balance(self): """获取当前余额""" return self.__balance # 实例化 BankAccount 对象 account = BankAccount() # 执行存款操作 account.deposit(100) # 存款 100 元 account.deposit(50) # 存款 50 元 # 执行取款操作 account.withdraw(30) # 取款 30 元 account.withdraw(150) # 尝试取款 150 元(余额不足) # 查看余额 print(f"当前余额: {account.get_balance()}元") # 尝试直接访问私有属性(将会失败) try: print(account.__balance) # 这将引发 AttributeError except AttributeError as e: print(e)代码说明
类定义:
BankAccount类具有一个私有属性__balance,初始值为 0。
方法:
deposit(amount):增加余额。如果存款金额大于 0,则增加余额并打印当前余额;否则,打印错误信息。withdraw(amount):从余额中扣除。如果余额不足,打印 "Insufficient funds";如果取款金额小于等于 0,打印错误信息;否则,扣除金额并打印当前余额。get_balance():返回当前余额。
实例化对象:
- 创建
BankAccount的实例account,并执行存款和取款操作。
- 创建
私有属性访问:
- 尝试直接访问私有属性
__balance,将引发AttributeError,因为私有属性不能在类的外部直接访问。
- 尝试直接访问私有属性
输出示例
运行上述代码后,你将看到类似以下的输出:
成功存款: 100元,当前余额: 100元 成功存款: 50元,当前余额: 150元 成功取款: 30元,当前余额: 120元 Insufficient funds 当前余额: 120元 'BankAccount' object has no attribute '__balance'总结
通过这个示例,你可以看到如何在 Python 中创建一个带有私有属性的类,并实现存款和取款的方法。同时,私有属性的访问限制确保了数据的封装性和安全性。
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报