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 trialAdiv Abramson
6,919 PointsCan an instance variable, e.g. self.xxx have the same name as a class variable? If so, is this a good practice?
Would the following code be OK?
class Widget():
weight = 10
length = 5
thickness = 2
widget_count = 0
def __init__(self, the_weight, the_length, the_thickness):
#do these assignments affect the class variables, which have
#the same name?
self.weight = the_weight
self.length = the_length
self.thickness = the_thickness
If an object is created from this class, do the properties refer to the class variables or the instance variables, e.g.:
my_widget = Widget(30, 110, 6)
my_widget.weight = #10 or 30? my_widget.length = # 5 or 110? my_widget.thickness = #2 or 6?
I know that Widget.widget_count returns 1 but is there a way to get to this class variable from within the object instance, e.g
my_widget.Parent.widget_count ?
Thank you
1 Answer
Kenneth Love
Treehouse Guest TeacherAnything assigned explicitly to self
will always refer to an instance, not the class.
To get back to the class, use self.__class__
or <instance>.__class__
where <instance>
is an instance... yeah.