Lesson 8
Making Objects the Main Star!
Chapter 8: Magic methods
Magic/dunder methods
You have seen the special constructor method __init__() earlier.
Python offers more magic or dunder methods that can be used to make your classes act like Python built-in types (dunder == double underscores).
Let’s look at a few example magic methods and how they can be useful.
A more readable str representation of an object.
We can use str() in Python to return a string representation of any objects. By default, str(your_instance) will return something like '<__main__.Person object at 0x7fa89a45a1f0>'. The print() function will also internally convert an object into a string before printing them out.
If you would like something more readable and informative, say "A Person named Josiah aged 20", you can override the default behaviour with a magic __str__() method.
Below is an example. Run the code with and without the __str__(self) method, and check the output to compare the difference!
1 2 3 4 5 6 7 8 9 10 | |
Try it yourself!
Now try making the Person class return a more readable and informative string representation of the object. For example, you could return something like "A Person named Josiah aged 20 from malaysia".
class Person:
def __init__(self, name, age, nationality="uk"):
self.name = name
self.age = age
self.nationality = nationality
def __str__(self):
# TODO: Complete this!
pass
lecturer = Person("Josiah", 20, "malaysia")
print(lecturer)
You can check your implementation against mine on the next page.