Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global variable Python classes

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() 
like image 844
nobody Avatar asked Jun 25 '11 02:06

nobody


People also ask

How do I use a global variable in a class Python?

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.

Can classes access global variables Python?

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.

Do classes have access to global variables?

You can access the global variables from anywhere in the program. However, you can only access the local variables from the function.


1 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,  # 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

like image 192
Anurag Uniyal Avatar answered Oct 23 '22 14:10

Anurag Uniyal