Computer >> Computer tutorials >  >> Programming >> Python

What is the proper way to define a global variable that has class scope in python?


The following code shows use of global variable in class scope.

Example

class Foo(object):
    bar = 2
foo = Foo()
print Foo.bar,
print foo.bar,
# setting foo.bar would not change class attribute bar
# but will create it in the instance
foo.bar = 3
print Foo.bar,
print foo.bar,
# to change class attribute access it via class
Foo.bar = 4
print Foo.bar,
print foo.bar

Output

2 2 2 3 4 3