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()
We declare a variable global by using the keyword global before a variable. All variables have the scope of the block, where they are declared and defined in. They can only be used after the point of their declaration.
As shown below, global variables can be accessed by any class or method within a class by simply calling the variable's name. Global variables can also be accessed by multiple classes and methods at the same time.
You can access the global variables from anywhere in the program. However, you can only access the local variables from the function.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With