This is the lecture note of CS61A - Lecture 18.
String Representations
An object value should behave like the kind of data it is meant to represent.
In Python, all objects produce two string representations:
- The str is legible to humans
- The repr is legible to the Python interpreter
🌋 The print()
function calls the built-in __str__
method of the object, while simply calling the object in interactive mode calls the built-in __repr__
method.
The str and repr strings are often the same, but not always.
1 | # Demo |
String Interpolation
1 | # Demo |
Polymorphic Functions
Let's see some examples.
1 | class Bear: |
1 | class Bear: |
1 | class Bear: |
To check our understanding, let's try to implement our repr
and str
function.
1 | class Bear: |
Let's see a demo.
1 | class Ratio: |
Special Method Names
Special method names are a topic particularly to the Python.
1 | class Ratio: |
🏝️ Supplement Link: What is the meaning of single and double underscore