I see this was flagged as a duplicate of "What is the difference between class and instance variables?" However I don't believe I'm using any instance variables in my example, neither of my classes has a __init__
I'm editing class variables in two different ways and trying to understand the difference between them, not the difference between a class and instance variable.
I'm trying to understand the difference between calling a class variable just with .var
and with .__class__.var
. I thought it was to do with subclassing so I wrote the following code.
class Foo:
foo = 0
class Bar(Foo):
bar = 1
def print_class_vals(f, b):
""" prints both instant.var and instant.__class__.var for foo and bar"""
print("f.foo: {}, {} "
"b.foo: {}, {} "
"b.bar: {}, {} "
"".format(f.foo, f.__class__.foo,
b.foo, b.__class__.foo,
b.bar, b.__class__.bar))
f = Foo()
b = Bar()
print_class_vals(f, b)
Foo.foo += 1
print_class_vals(f, b)
Bar.foo += 1
print_class_vals(f, b)
Bar.bar += 1
print_class_vals(f, b)
This outputs the following:
f.foo: 0, 0, b.foo: 0, 0, b.bar: 1, 1
f.foo: 1, 1, b.foo: 1, 1, b.bar: 1, 1
f.foo: 1, 1, b.foo: 2, 2, b.bar: 1, 1
f.foo: 1, 1, b.foo: 2, 2, b.bar: 2, 2
I can't seem to find any difference between calling inst.var
and inst.__class__.var
. How are they different and when should I use one over the other?