Accessing attributes that don't exist
Sometimes, you may try to access an attribute that does not exist in the namespace for an object. When this happens, typically, an AttributeError is thrown. In this exercise, you'll practice handling this scenario using one of Python's magic methods. Enjoy!
Este exercício faz parte do curso
Intermediate Object-Oriented Programming in Python
Instruções do exercício
- Define a method to be executed when referencing an attribute not defined in the
BankAccountnamespace; this method should take parametersselfandname. - Add logic to the magic method to print a message suggesting the attribute referenced should be set for the object.
- Create an object of the
BankAccountclass, and attempt to access therouting_numberattribute; observe the output.
Exercício interativo prático
Experimente este exercício completando este código de exemplo.
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")
____.____