DEV Community

gaotter
gaotter

Posted on

Classes variables early thoughts 🤔

I'm just starting to learn Python, coming from languages like C# and JavaScript/TypeScript. I'm going thought this https://docs.python.org/3/tutorial/index.html tutorials. I gotten to the classes section. One thing I kinda felt can be a little risky thing to use is the class variables. In that you can loose the control of state of the objects in you code, when using them.

Here is the Dog example that is in the Python tutorial.

class Dog:
    kind = 'canine'

    def __init__(self, name):
        self.name = name
Enter fullscreen mode Exit fullscreen mode

I make to instances of the dog class

fido = Dog('Fido')
buddy = Dog('Buddy')

print(fido.kind) // prints canine
print(buddy.kind) // prints canine
Enter fullscreen mode Exit fullscreen mode

All is fine, I know what kind is going to be. In the tutorial it states that the class variables a shared between instances of the class. Like this

Dog.kind = 'dog'

print(fido.kind) // prints dog
print(buddy.kind) // prints dog
Enter fullscreen mode Exit fullscreen mode

But if i set kind on one of the instances, the instance 'looses' shared kind

fido.kind = 'super dog'
Dog.kind = 'dog'

print(fido.kind) // prints super dog
print(buddy.kind) // prints dog
Enter fullscreen mode Exit fullscreen mode

In a large code base, one can easily loose track of the kind variable. One can't really trust the variable, as it can either be changed by the shared class variable, or some code has set the instance variable.

One can marking as private using _kind to tell to other developers that is should thought of as private, but still one can easily miss use it. Unsure if I ever would want to us it an public way. But still new to Pyhon so still learing.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay