Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Object-Oriented Python Instant Objects Method Arguments

Guillaume Crt
Guillaume Crt
6,395 Points

About 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

Hi 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
Guillaume Crt
6,395 Points

I 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 ?