u09_slides-advanced-classes-flashcards
What is the root/base class for all Python classes?
The ‘object’ class - all classes inherit its special methods
What happens by default when using == to compare custom class instances?
It falls back to a reference/identity check (equivalent to ‘is’ operator)
What is operator overloading?
Changing the default behavior of operators (like ==, +, *) for custom classes by implementing special methods
What special method is called when using the == operator?
__eq__(self
What should __eq__ return if the comparison isn’t supported?
Return NotImplemented
What special method enables addition (+) for custom classes?
__add__(self
What special method enables multiplication (*) for custom classes?
__mul__(self
What special method enables index access ([]) for custom classes?
__getitem__(self
What special method enables the ‘in’ operator for custom classes?
__contains__(self
How do you make a custom class iterable (usable in for loops)?
Implement __iter__(self) method
How do you enable context manager support (with statement)?
Implement both __enter__(self) and __exit__(self, exc_type, exc_value, traceback) methods
How do you make an object callable like a function?
Implement __call__(self
What special method is used for hashing objects?
__hash__(self)
What special method is used for string representation?
__str__(self)
What special method is used for less than comparisons?
__lt__(self
Where can you find the specifications for special methods?
Python’s data model documentation (docs.python.org/3/reference/datamodel.html)
Does the object class have any attributes that are inherited?
No - object has no instance attributes that are inherited
When implementing __eq__ what’s a good practice to include?
Check if the other object is an instance of the same class using isinstance()
What happens when you use == between objects?
Python automatically translates it to a call to __eq__(self
What are special methods primarily used for?
Enabling Python-specific behaviors and features for custom classes, like operators and built-in function support