ComeçarComece de graça

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

Ver curso

Instruções do exercício

  • 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.

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")
____.____
Editar e executar o código