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 Basic Object-Oriented Python Welcome to OOP Methods

Why do you set attributes in __intit__ and in methods?

In the video Megan set

def init(): self.is_moving = False

Then she modified a method

def stop (self): if self.is_moving: print("The car is stopped") is_moving= False else: print ("The car has stopped")

is_moving is defined in the init so why do we have to define it again in the method.

Thanks for the explanation in advance!

2 Answers

Hi Cylin,

The init method only occurs once and that's when we create an instance of a class. So in this example, you can think of it as when we create a Car object the car starts off as not moving, hence the self.is_moving = False

So an instance of a Car will always start off with the is_moving attribute as False. Now in our other methods stop() and go() that changes the behavior of our car object so we also need to modify our is_moving variable; that is why you see they get reassigned to True or False values accordingly.

Vincent Zamora
Vincent Zamora
3,872 Points

I maybe wrong but In the init initializes the call which would also include defaults. The setter methods would actually change the values of the attributes.