Good day. The question arose how good practice is to use a class variable as a kind of global variable?

Let me explain with an example. For my one task, I had to create a class whose objects would receive a unique number when created. I did it like this:

class A(object): _counter = 0 def __init__(self): self.id = A._counter A._counter += 1 

It works, but how good is it in terms of the correct principles of architecture?

This is something very similar to a global variable.

But it can be done to make instances of an object not only received students in such a way, but then communicate with other instances through class variables. How right to do so?

And if we put in a variable not just a value, but a complex object, then it will generally turn out to be a singleton.

And not only its instances, but also some external code can access a class variable. So, probably, you should not do at all?

  • Classes for this purpose also were created to transfer and interact with difficult objects. For simple variables, the best counter is global. Explicit is better than implicit. Simple is better than complicated. Complicated is better than confusing. - Igor
  • It seems to me that answering this question is all exactly what to answer the question "why are static variables in a class necessary." - Max

1 answer 1

 import uuid class A(object): def __new__(cls): ob = object.__new__(cls) setattr(ob, 'uuid', uuid.uuid1().__str__()) return ob o1 = A() o2 = A() print(o1.uuid, o2.uuid) 43fcaa9a-63ac-11e6-9057-1c6f6592d67b 43fd46da-63ac-11e6-97a8-1c6f6592d67b 

it is possible and so, but why

  • so why not, but if you add a compound object, it will be why. - Igor