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 trialLeo Marco Corpuz
18,975 Points__class__.__name__?
I don’t understand why __class__.__name__
is referring to the name of the class(‘Thief’). It looks like it’s accessing the name attribute.
2 Answers
Chris Freeman
Treehouse Moderator 68,457 PointsGood question!
In self.__class__.__name__
:
- "self" is represents the instance of the class:
kenneth
- The attribute
__class__
is set to thetype
of the instance. In this case it is set to point to theThief
class obj:kenneth.__class__
returns<class '__main__.Thief'>
- When the class instance is initiated, the
__name__
attribute of the__
class__
is assigned to the name "Thief":kenneth.__class__.__name__
returns "Thief
"
Answering anthony pizarro:
What does **__ do? Can anything be __x__
?**
The double underscores __ beginning and ending a method name is a naming convention signifying this method is one of the special methods predefined within the Python language. They are also nicknamed “dunder” method for double underscore. See Python data model for complete list. It is not recommended to create your own new dunder method.
What is the “.” for?
The dot (“.”) syntax is used to mean “an attribute of”. So the code
self.__class__"."__name__
would mean, the __name__
attribute of the __class__
attribute, of self
which is the current instance of the class
What if i had two files one for Thief and another for Pirate?
In both cases, the __class__.__name__
would be set to the name of the defined class. So Thief
and Pirate
would get the correct name.
As always, post back if you have more questions. Good Luck!!
anthony pizarro
1,983 Pointswhat if i had two files one for Thief and another for Pirate.
if i use self.__class__"."__name__
, self.name
how would the program know which file to use.
would there need to be a new line of code in def __init__ (self....)
asking for a character?
and why do we use __class__
, what does __
actually do
can anything be __x__
i have re watch the video over and over again , but i dont understand what hes doing or why there's a period in there ""
[MOD: Edited for clarity -cf]
Chris Freeman
Treehouse Moderator 68,457 PointsSee updated answer above.