Search code examples
pythonclassstatic-methodsstatic-variables

Populate once static variable from static method Python within a class


I have a Class A in Python and I would like to populate the a static variable calling a static method like:

Class A:
   arr = []

   @staticmethod
   def FillArr():
       #do more stuff but for semplicity...
       A.arr = [[2,2,2,]]

  FillArr.__func__()

when I run the code I got 'NameError: name A not defined' so essentially I can't initialize the arr static variable. Essentially once the the class has been instantiated once I would like to populate the static variable


Solution

  • This runs flawlessly on Python 3.6:

    class A:
       arr = []
    
       @staticmethod
       def fillArr():
           #do more stuff but for simplicity...
           A.arr = [[2,2,2,]]
    
    A.fillArr()
    
    print (A.arr)
    

    Or, with the extra info in your comment:

    class A:
        arr = []
    
        @staticmethod
        def fillArr():
            #do more stuff but for simplicity...
            A.arr = [[2,2,2,]]
    
        def __init__ (self):
            if not A.arr:
               A.fillArr ()
    
    A ()
    
    print (A.arr)