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 trialGuillaume Crt
6,395 PointsAbout sneaky attribute
Can someone explain to me how the class attribute and the instance attribute are related and why we are using them that way in the example ? Thanks
2 Answers
Peter Vann
36,427 PointsHi Guillaume!
Think of class attributes as common properties shared by any/all instances of a class and instance attributes as distinct properties unique to individual class instances.
For example, if you have, say, a car class, all cars will have 4 wheels - so that would make a logical class attribute (as would windshield, body, hood, trunk, etc.) and/or even a "drive" function.
But individual cars might have different makes, models, colors, etc., so those would make logical instance attributes.
In this case "sneaky" kind of straddles the fence.
All thieves will have a sneaky attribute, that by default is True, but individual instances have the option to toggle "sneaky" between True and False.
A similar case would be a class that included a counter. All instances will have a counter, but over the life cycle of each instance, their respective counters might have different values.
In the case of a car, examples might be fuel/gas and mileage (odometer reading), and perhaps needsOil (a boolean attribute). All cars will have those attributes, but they will likely have different values for each instance.
Does that make sense?
More info:
https://medium.com/@mohamethseck/class-and-instance-attributes-bb2ab2a36227
https://realpython.com/lessons/class-and-instance-attributes/
I hope that helps.
Stay safe and happy coding!
Guillaume Crt
6,395 PointsI think I didn't explain myself right, sorry. What I meant is , I write that (like the example of the lesson) :
class Thief
sneaky = True
def __init__(self, name, sneaky = True):
self.name = name
self.sneacky = sneacky
every thief has a sneacky attribute set to True. But I'd rather write simply that :
class Thief
def __init__(self, name, sneaky = True):
self.name = name
self.sneacky = sneacky
is there a difference regarding initializing sneacky ?