Reputation: 3101
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
Upvotes: 1
Views: 2466
Reputation: 5472
Use @classmethod:
class A(object):
arr = []
@classmethod
def FillArr(cls):
cls.arr = [[2,2,2]]
A.FillArr()
print A.arr
This will result in: [[2,2,2]]
/edit/ the using normal method example I mention in my comment below (based on Jacques explanation):
class A
arr=[]
def FillArr(self):
self.arr = [[2,2,2,]]
def __init__(self):
self.FillArr()
a = A()
print a.arr
Upvotes: 2
Reputation: 7000
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)
Upvotes: 3