47

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()
1
  • 11
    If the answer below as correct you should accept it as such Commented May 13, 2015 at 22:14

1 Answer 1

104

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

Sign up to request clarification or add additional context in comments.

5 Comments

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 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 Refer to python documentation 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'
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'?
What happens if I import the Shape from multiple threads or files? Will the variable lolwut be still global (common across the threads)?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.