Source: https://docs.google.com/presentation/d/1vRgHqvw7YxlADO_tKuuNWONEkH1onKFwYxtCT9kFCcU/edit#slide=id.p1 (cont.)
Special Methods
Special Method Names in Python
__init__: Method invoked automatically when an object is constructed
__repr__: Method invoked to display an object as a Python expression
__add__: Method invoked to add one object to another
__bool__: Method invoked to convert an object to True or False
__float__: Method invoked to convert an object to a float (real number)
Implementing str and repr
Implementing
strandreprThe behavior of
stris complicated:
- An instance attribute called
__str__is ignored- If no
__str__attribute is found, usesreprstring- By the way,
stris a class, not a function
- When you call
str, you call a constructor for the built-in string type calledstr