Source: https://docs.google.com/presentation/d/1vRgHqvw7YxlADO_tKuuNWONEkH1onKFwYxtCT9kFCcU/edit#slide=id.p1
String Representation and Special Methods
String Representations
- An object value should behave like the kind of data it is meant to represent
- For instance, by producing a string representation of itself
In Python, all objects produce two string representations- The
stris easy for humans, to be readable
- Informal representation
- The
repris easy for the Python interpreter
- Official representation
The
reprString for an ObjectThe result of calling
repron a value is what Python prints in an interactive session
Some objects do not have a simple Python-readable string
Thereprfunction returns a Python expression (a string) that evaluates to an equal object (same object when passed toeval()): https://docs.python.org/3/library/functions.html#repr
- i.e.
eval(repr(object)) == object
eval()utility which lets Python program run Python code within itself, by evaluating expressions.
- It is used on sites like codepad.org to allow you to execute scripts in a test environment.
eval(expression, globals=None, locals=None)- expression: this string is parsed and evaluated as a Python expression
- globals (optional): a dictionary to specify the available global methods and variables
- locals (optional): another dictionary to specify the local methods and variables
Polymorphic Functions
Polymorphic function: a function that applies to many (poly) different forms (morph) of data
strandreprare both polymorphic; they apply to any object
reprasks an argument to display itself
invokes a zero-argument method__repr__on its argument
User-defined classes
- Need to have methods
__str__and__repr__in order to be able to print string representation of an object.- If
__str__does not exist, then__repr__will be used- At the very least, you should implement
__repr__