从类中的静态方法 Python 填充一次静态变量 [英] Populate once static variable from static method Python within a class
本文介绍了从类中的静态方法 Python 填充一次静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 Python 中有一个 A 类,我想填充一个调用静态方法的静态变量,例如:
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__()
当我运行代码时,我得到NameError: name A not defined",所以基本上我无法初始化 arr 静态变量.基本上一旦类被实例化,一旦我想填充静态变量
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
推荐答案
这在 Python 3.6 上完美运行:
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)
这篇关于从类中的静态方法 Python 填充一次静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文