Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python (retired) Inheritance Instance Methods

dunder init - why don't you have to call the function?

when utilizing the init method (init), why don't you need to call the function? for example, this code is inside a class. however, the dunder init function will run without being called.

def init(self, **kwargs): self.name = input("Name: ") self.weapon = self.get_weapon()

1 Answer

Steven Parker
Steven Parker
231,271 Points

:point_right: The __init__ function is called when you create an instance of the class.

You may not be explicitly calling it in your code, but when you create a new instance of the class, it is invoked for you as part of the process.

This is actually just one of a number of class methods sometimes called "magic methods". They all have names using the "dunder" format, and are all invoked implicitly when something is done with the class. They each have a default that is performed if you don't define them yourself, but when you do define them you can take control of some particular operation. Details on each of them can be found (as "special methods") in the official Python documentation.

oh that makes sense. Thanks so much!