Global variable Python classes

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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

Coming from a C/C++/Java background I assume that this is correct:

class Shape:
    lolwut = None

    def __init__(self, default=0):
        self.lolwut = default;
    def a(self):
        print self.lolwut
    def b(self):
        self.a()

Answers

What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut or via an instance e.g. shape.lolwut but be careful while setting it as it will set an instance level attribute not class attribute

class Shape(object):
    lolwut = 1

shape = Shape()

print Shape.lolwut,
print shape.lolwut,

# setting shape.lolwut would not change class attribute lolwut 
# but will create it in the instance
shape.lolwut = 2

print Shape.lolwut,
print shape.lolwut,

# to change class attribute access it via class
Shape.lolwut = 3

print Shape.lolwut,
print shape.lolwut

output:

1 1 1 2 3 2

Somebody may expect output to be 1 1 2 2 3 3 but it would be incorrect

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/6475321/global-variable-python-classes

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils