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) Objects __init__

use of "self"

I'm confused as to what exactly self is, and when/why we need to use it. For example, in this code, why do we need to put it in the parentheses and then again in the lines below?

def __init__(self, **kwargs):
    self.hit_points = kwargs.get('hit_points', 1)
    self.weapon = kwargs.get('weapon', 'sword')
    self.color = kwargs.get('color', 'yellow')
    self.sound = kwargs.get('sound', 'roar')

1 Answer

Steven Turturo
Steven Turturo
6,890 Points

self is in reference to an instance of a Class. Think of it as signing up for a website and you pass on your information into a sign-up form (you are creating an instance of yourSELF on the web). In the form for fields you pass on self.first_name, self.last_name, self.email as you initialize the instance of the class. You need to pass it into the init method in order to access and set the variables to the kwargs. I hope my very broken explanation helps.

thanks so much! that's a really helpful analogy.

Kathryn

Steven I have to agree, a very nice explanation.