Bummer! You must be logged in to access this page.

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

Didn't get anything about __init__ methods 🤔

I rewatched this video for a few times already - still not clear for me what is it for and how it works

1 Answer

Python's init method gives you a way to set attributes when creating a class instance. Let's say you have a class named "Person". If you were to define your class like this:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

You would be able to set the name and age attributes when creating a Person instance

>>> me = Person('Matt', 29)
>>> me.name
'Matt'
>>> me.age
29

Some links for further reading:

https://pymbook.readthedocs.io/en/latest/classes.html

https://micropyramid.com/blog/understand-self-and-__init__-method-in-python-class/

https://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do

I hope this helps! Let me know if you have any questions.