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 Push My Buttons

Brandon Wall
Brandon Wall
5,512 Points

Assign this to self so we can get back to it later?

When we build the function build_buttons, there is a moment in the video at 2:0something, cant see because this window is in the way, but its in the first 10 seconds of the 2 minute mark where Kenneth Love defines self.start_button and i believe he is saying "And we're going to assign this to self so we can get back to it later"

What exactly does that mean? I'm still having trouble understanding the whole self argument on methods. I've read a lot about them, scoured the web for info, i know it's referring to the instance of the class that the method is called on...but i still don't really understand.

What would happen if we defined start_button without the self argument?

1 Answer

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

self points back to the current instance. So it's the instance of our app that's running and that all of the methods in our app's class know about. Since we want to be able to get back to those buttons from other methods, without having to provide them to those methods, we stick them onto the instance so they'll be available.

If we didn't assign them to self, and we just made it as start_button, it wouldn't exist anywhere outside of that method and we wouldn't be able to get to it again later.

Brandon Wall
Brandon Wall
5,512 Points

So self is sort of expanding the scope of our variable within the method so it is able to be referenced anywhere in the instance of a class? If we didn't give it an explicit self, then the scope of that widget would only be accessible from within that method, and we would have to define it again and again on different methods? Am I on the right track? I think i got it :D

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

It's not really changing the scope of the variable, but, yeah, that's the general idea.