45

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()
nobody
  • 451
  • 1
  • 4
  • 3

1 Answers1

100

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,  # 1
print shape.lolwut,  # 1

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

print Shape.lolwut,  # 1
print shape.lolwut,  # 2

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

print Shape.lolwut,  # 3
print shape.lolwut   # 2 

output:

1 1 1 2 3 2

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

Jimmy Huch
  • 4,400
  • 7
  • 29
  • 34
Anurag Uniyal
  • 85,954
  • 40
  • 175
  • 219
  • 1
    I test your example in python 2.7, it's all right. But When you first set value to the Shape.lolwut, and the instance value will be changed.Once you set value to the instance attribute, the two will not be same even you change the value of the class level, just like you example. – Danyun Liu Apr 16 '12 at 02:46
  • @Danyun I tested as well. I saw the same situation as you mentioned. Do you know why it happens like that? When you changed the attribute from class level will change instance's as well. But when you change instance level at first, then change from Class level, it will not affect instance again. – user1167910 Nov 21 '15 at 21:20
  • @user1167910 Refer to python documentation https://docs.python.org/2.7/reference/datamodel.html, you will find 'Attribute assignments and deletions update the instance’s dictionary, never a class’s dictionary' – Danyun Liu Nov 22 '15 at 07:52
  • So it means... creating an instance will not help you in the global variable, but only change the variable in the class directly will achieve the goal of setting 'global variable'? – ArtificiallyIntelligence May 25 '16 at 22:49
  • What happens if I import the Shape from multiple threads or files? Will the variable lolwut be still global (common across the threads)? – user1315621 Mar 10 '21 at 19:12