filmov
tv
What If An Attribute Doesn't Exist? __getattr__() #shorts #python #pythonforbeginners

Показать описание
What if we try to access an object attribute that doesn't exist?
Well, if we do nothing, our program will simply fail. We'll get an AttributeError.
We can make our class handle such things by overriding the __getattr__ method. Instead of crashing we can perform some operation if someone/something tries to access a non-existent attribute.
In this example, we just return a string that we then print to the console. But we could put anything we like here depending on our needs and use case.
Well, if we do nothing, our program will simply fail. We'll get an AttributeError.
We can make our class handle such things by overriding the __getattr__ method. Instead of crashing we can perform some operation if someone/something tries to access a non-existent attribute.
In this example, we just return a string that we then print to the console. But we could put anything we like here depending on our needs and use case.