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
I make to instances of the dog class
fido = Dog('Fido')
buddy = Dog('Buddy')
print(fido.kind) // prints canine
print(buddy.kind) // prints canine
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
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
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.
Top comments (0)