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) Inheritance Instance Methods

Chih-Wei Hsu
Chih-Wei Hsu
11,132 Points

adding self before a variable name

i've noticed that when defining the get_weapon method, the variable name weapon_choice was not preceded with self. Do we only need to add self. for variables defined under the __init__ method ??

[MOD: added ` ` around __init__ -cf]

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The self represents the instance of a class being referenced. If it is used as a prefix for a variable name, then the variable is an attribute (or method) of that instance. During __init__, instance attributes are being define, so self is needed. Attributes are persistent.

In other cases, if a variable is only being used as an method argument or a temporary variable within a method, it doesn't have the self. prefix and is a local variable. That is, it disappears after the method is finished (it is non-persistent).

Chih-Wei Hsu
Chih-Wei Hsu
11,132 Points

thank you for the very clear explanation!