Simply
Foo.var
changes class state.
self.var
changes object state.
class Foo():
var = None
def __init__(self):
Foo.var = 1
class Bar():
var = None
def __init__(self):
self.var = 1
print('Foo before', Foo.var)
print('Bar before', Bar.var)
foo = Foo()
bar = Bar()
print('foo', foo.var)
print('bar', bar.var)
print('Foo after', Foo.var)
print('Bar after', Bar.var)
Foo.var = 2
Bar.var = 2
print('foo after class changed', foo.var)
print('bar after class changed', bar.var)
output:
Foo before None
Bar before None
foo 1
bar 1
Foo after 1
Bar after None
foo after class changed 2
bar after class changed 1
About second question:
Is Example 1 a static variable or is it an incorrect use of a variable declaration as a static variable?
Both var
s are static (or class) variables. You able to call them without creating instance. (Foo.var
, Bar.var
)
class Foo():
class_variable = 'c'
def __init__(self):
self.instance_variable = 'i'
print('Class variable of class', Foo.class_variable)
try:
print(Foo.instance_variable)
except Exception as e:
print('This error happens when we call instance variable without creating instance')
print(e)
instance = Foo()
print('Class variable of instance', instance.class_variable)
print('Instance variable of instance', instance.instance_variable)
Class variable of class c
This error happens when we call instance variable without creating instance
type object 'Foo' has no attribute 'instance_variable'
Class variable of instance c
Instance variable of instance i