Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Python's Magic Methods in Classes (Summary)

You now know how to customize your classes using special methods, also known as magic methods or dunder methods in Python. These methods support core object-oriented features in Python, so learning about them is a fundamental skill for Python programmers who want to create powerful classes in their code.

In this video course, you’ve learned:

  • What Python’s special or magic methods are
  • What the magic behind magic methods in Python is
  • How to use special methods to customize different class’s behaviors

With this knowledge, you’re now ready to deeply customize your own Python classes by leveraging the power of special methods in your code.

Download

Course Slides (.pdf)

5.6 MB
Download

Sample Code (.zip)

3.3 KB
Avatar image for taniferf

taniferf on Oct. 30, 2024

For me, the biggest take away is the understanding of ‘init()’ and the ‘str()’ dunder methods.

Avatar image for bhchurch6

bhchurch6 on Nov. 6, 2024

I created the Storage class without saving the ‘value’ attribute in the instance since it should have been created by the super().__new__(class, value).

class Storage(float):
    def __new__(cls, value, unit):
        instance = super().__new__(cls, value)
        instance.unit = unit
        return instance
    def __str__(self):
        return f'{super().__repr__()} {self.unit}'

When I created the object >>> storage_size = Storage(512, 'GB'), entering just storage_size in the repl, the value ‘512’ was printed out. So the value was available from the object. Using the print() function, the output was 5120 GB as per the __str__ method.

When I tried to create the __repr__ method in a similar fashion, I got a recursion error. With my modified class object, how do I get the underlying float value from the inherited class from the __repr__ method’s ‘self’ object. I thought that including an instance.value attribute was essentially duplicating the underlying float value provided by the inherited class.

Avatar image for ole088

ole088 on Nov. 12, 2024

Great course, Negar!! I like how you introduced and explained things. I have used some of these magic methods in the past, but will be using them more in the future. I look forward to more courses from you!

Become a Member to join the conversation.