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!
Cet exercice fait partie du cours
Intermediate Object-Oriented Programming in Python
Instructions
- Define a method to be executed when referencing an attribute not defined in the
BankAccount
namespace; this method should take parametersself
andname
. - 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
BankAccount
class, and attempt to access therouting_number
attribute; observe the output.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
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")
____.____