Open Source Your Knowledge, Become a Contributor
Technology knowledge has to be shared and made accessible for free. Join the movement.
"Magic Methods" or "Dunder Methods" of Python Classes
__str__ method of the Fruit class has been overridden for a formatted string representation.
__eq__ method has been overridden to check the equality of objects.
Note that in the
__eq__ method, we ensure that the passed other object is of the correct type before checking equality (
isinstance()) to avoid errors.
__getitem__, we can retrieve the attribute values of a Fruit object using a key, and with
__setitem__, we can update the attribute values using a key. This allows us to access and modify the attributes of an object as if it were a dictionary.
If you want a more complex example (external libraries, viewers...), use the Advanced Python template