Static variable in Python

Asked

Viewed 3,300 times

4

I came from Java. I have a variable in a class that I need to change in more than one method.

I tried to put it global, but it consumes a lot of resource.

  1. How to implement this?
  2. It would be the same as a static variable in Java?
  3. How to modify var from another class in Django?

    var = 0
    def metodo1():  
    var += 1      
    def metodo2():  
    var += 10
    

[Resolved]

Thank you for the answer of the colleague below. I resolved as follows: I created a static class':

class Modulo(object):
    andamento_processo = 0
    def processo(self):
        self.andamento_processo = 1

Now I urge her from the other class and change the value when I need it, it’s literally like a static variable (from java)!

class NovaClasse:
    Modulo.andamento_processo = 10
  • Beware of variables created in the Python class body: are attributes of class and not instance attributes, as in Java. The above example and the answer work, but they would work without class variables - I recommend leaving them out if they’re not exactly what you want. (And no, a "global" variable in Python is just an attribute of the module object, not something as "terrible" as a global variable in C. Having a class just to have an attribute you can modify can be a bad practice in Python. Or it can be a good one in the case of several groups of variables in the same module

1 answer

3

Object Orientation in Python is a little different. If you create a variable it is accessible by default. The difference is as follows: If the variable is accessed by an object instance, it is object attribute, otherwise it is class attribute.

Example:

class A(object):
   variavel = 1

This way is object:

objeto = A()
objeto.variavel

Otherwise it would be a very similar artificial to Java (as you want):

A.variavel

To try to clarify, imagine that your class has an initializer that changes the value of the variable from 1 to 5. When calling the first code I showed will be returned 5, if the second code is called, it will return 1.

#!/usr/local/bin/python2.7

class A(object):
  variavel = 10

  def __init__(self):
    self.variavel = 15


print A.variavel #resultado 10
print A().variavel #resultado 15

Source for more information: Static variables and methods in Python

Browser other questions tagged

You are not signed in. Login or sign up in order to post.