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 trialEdan Leibovitz
4,958 Pointswhy did you define class variable and instance variable with the same name- sneaky?
Why did you define class variable and instance variable with the same name- sneaky? Isn't it that the instance variable shadows the class variable? If so, the class variable has no actual meaning.
2 Answers
Chris Freeman
Treehouse Moderator 68,457 PointsThe class attribute is still present even if the instance attribute has the same name. When looking up values, Python checks the instance then the class attributes.
# a simple class with one attribute
class ClassOne:
color = "white"
def __init__(self, color, **kwargs):
self.color = color
for key, value in kwargs.items():
setattr(self, key, value)
>>> c = ClassOne("red")
>>> c.color
"red"
>>> del c.color # delete instance attribute
>>> c.color
"white"
>>> ClassOne.color
"white"
nuri jeon
14,376 PointsAha :D thanks ! I was wondering about the same stuff! XD yay