Static Variable in Python

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 consumed a lot of resources.

  • How to implement this?
  • Would it be the same shape as a static variable in Java?
  • How do I change var of another class in Django?

    var = 0
    def metodo1():  
    var += 1      
    def metodo2():  
    var += 10
    
  • [ Resolved ]

    Thanks for your colleague's reply below. I have decided as follows: I created a 'static' class:

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

    Now I instantiate it from the other class and change the value when it needs it, it literally looks like a static (java) variable!

    class NovaClasse:
        Modulo.andamento_processo = 10
    
        
    asked by anonymous 17.04.2014 / 02:29

    1 answer

    3

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

    Example:

    class A(object):
       variavel = 1
    

    That way it's an object:

    objeto = A()
    objeto.variavel
    

    In this way, it would be a device very similar to Java (as you want):

    A.variavel
    

    To try to make it clear, imagine that your class has a 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

        
    17.04.2014 / 13:11