Difference between global class variables and init variables

I’m coming from a Java/C# background and I don’t understand the reason for having global variables outside the init function (method?).
I’m used to having constructors that initialize as many global variables as needed that are declared above and outside my constructor.
In Python it seems that global variables can be created both in and out of init, the only difference being that variables inside init need self. and all objects of the class have a common value for variables outside init. So each init variable value is unique to the class object, and each global var value outside init is common to every object.

Is this correct? I read init is not a constructor in the C# sense, but it pretty much is the same functionally. Why would I want this different behavior?

1 Like

Global variables written in the global namespace are universally global. All others are scoped to their blocks.

A class variable is scoped to the class but accessible to all instances of the class. __init__ variables are unique to each instance. Class variables are private, whereas instance variables are public.

Class variables must be accessed by methods in the class since they have no self dictionary instanced to the outside.

1 Like

So private condition must be accessed by a method, whereas public model, color, and mpg can be accessed from outside, correct? Why can I reference these two types the same way and have them both return their values instead of just the public variables?

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg = mpg
my_car = Car("DeLorean", "silver", 88)
print my_car.condition
print my_car.model


1 Like

I think I spoke rather quickly, and don’t mind admitting that. What we cannot do is access Car.condition, and must have an instance through which we can access it. Was confusing JavaScript private variables with Python class variables. My apologies.

1 Like