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 trialAndrew Leibowitz
2,529 PointsWhy do you need the self attribute in the __init__ function?
This was the code
class Car:
wheels = 4
doors = 2
engine = True
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
1 Answer
Chris Freeman
Treehouse Moderator 68,454 PointsHey Andrew Leibowitz, thatβs a great question.
With multiple instances of a class, one might think there would a copy of an class method for each instance created. While certainly possible, this could greatly increase the memory requirements of a program. Instead, each method is constructed in a more generic fashion where a parameter is used to hold the instance reference. If the code within the method needs to refer to attributes of the instance, the instance reference parameter is used to indicate which instance the method code refers to.
The first parameter of a class method (a function defined inside of a class) is a placeholder for this instance reference. During code execution, the first parameter is automatically set to the instance reference. The context of your program indicates which instance reference should be used.
This first parameter can be named anything. It is only a convenient that Python programmers use self
to refer to the instance reference parameter.
You may hear the the term bound used to refer to a class method. This means there is a method parameter (self
) being use to βbindβ the method to a specific instance. A generic function that youβve learned abound in Basic Python, is unbound, that is, not associated with a class instance and does not have the instance reference placeholder.
The is more information about class structure in the docs.
When you get to the topic of class methods, they will also need a placeholder for the class reference. In this situation the convention is to use cls
as the parameter name. This method is bound to the enclosing class.
Post back if you need more help. Good luck!!!
Andrew Leibowitz
2,529 PointsAndrew Leibowitz
2,529 PointsThanks that makes more sense now!!