访问不存在的属性
有时,您可能会尝试访问对象命名空间中不存在的属性。通常情况下,这会抛出 AttributeError。在本练习中,您将练习使用 Python 的一种魔术方法来处理这种情况。开始吧!
本练习是课程的一部分
Python 面向对象编程进阶
练习说明
- 定义一个方法,当引用
BankAccount命名空间中未定义的属性时执行;该方法应接收参数self和name。 - 在该魔术方法中添加逻辑,打印一条消息,提示应为该对象设置所引用的属性。
- 创建一个
BankAccount类的对象,并尝试访问routing_number属性;观察输出。
交互式实操练习
通过完成这段示例代码来试试这个练习。
class BankAccount:
def __init__(self, account_number):
self.account_number = account_number
# Define a magic method to handle references to attribute
# not in an object's namespace
def ____(____, ____):
# Output a message to instruct further action
print(f"""{____} is not defined in BankAccount object.
Please define this attribute if needed.""")
# Create a BankAccount object, reference routing_number
checking_account = ____("123456")
____.____