Get startedGet started for free

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!

This exercise is part of the course

Intermediate Object-Oriented Programming in Python

View Course

Exercise instructions

  • Define a method to be executed when referencing an attribute not defined in the BankAccount namespace; this method should take parameters self and name.
  • 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 the routing_number attribute; observe the output.

Hands-on interactive exercise

Have a go at this exercise by completing this sample 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")
____.____
Edit and Run Code