Python - 静态类变量

标签 python class static

我有 C++ 背景,经常使用静态变量来减少必须初始化变量的时间数量(特别是在初始化需要很长时间的情况下)。因此,从 StackOverflow 上的其他帖子中,人们建议使用静态类变量,如下所示:

class MyClass(object):

    StaticList1 = [...] # Very large list
    StaticList2 = [...] # Very large list

现在,如果在程序执行过程中至少存在 1 个 MyClass 实例并且列表仅创建一次,那就没问题了。但是,如果在执行的某个阶段没有 MyClass 实例,Python 似乎会删除静态列表(我假设是因为引用计数器下降到 0)。

所以我的问题是,是否有任何简单的方法,无需使用外部模块来初始化 StaticList1 和 StaticList2 仅一次(第一次使用它们),并且永远不会删除它们,即使没有 MyClass 实例,直到程序存在(或您手动删除列表)?

编辑:

也许我把这个问题过于简单化了。我在做什么:

class MyClass(object):

    StaticList = None

    def __init__(self, info):
        if self.StaticList == None:
            print "Initializing ..."
            self.StaticList = []
            # Computationally expensive task to add elements to self.StaticList, depending on the value of parameter info

    def data(self):
        return self.StaticList

我从另一个脚本导入模块并有一个像这样的循环:

import myclass
for i in range(10000):
    m = myclass.MyClass(i)
    d = m.data()
    # Do something with d.

静态列表的初始化大约需要 200 - 300 毫秒,并且在循环的每次迭代中执行,因此循环需要很长时间才能完成。

最佳答案

虽然你的类确实有一个名为 StaticList 的静态字段,您实际上正在初始化并使用同名的实例字段,因为 self您正在使用的限定符。我认为如果你使用 MyClass.StaticList 你的代码会正常工作来初始化并访问它。

一般来说,通过 Python 的名称查找,您可以通过实例访问类字段,就好像它是该实例上的实例字段(例如 self.StaticList )只要您没有'实际上在该实例上设置了同名的实例字段。从那一刻起,实例字段将隐藏类字段(即 self.StaticList 将找到您的新值,而 MyClass.StaticList 仍将引用您的类值)。

作为来自解释器的新示例:

>>> class A(object):
...  v=2      # static initialization
...
>>> A.v
2
>>> a=A()     # get an instance, and
>>> a.v       # get the static value via the instance:
2
>>> a.v = 7   # but now set 'v' on the instance, and ...
>>> a.v       # we will get the instance field's value:
7
>>> A.v       # the static value is still the old:
2
>>> b=A()     # and other instances of the class ...
>>> b.v       # will use the same old static value:
2

实例变量a.v最初等于 A.v ,但通过显式设置 a.v=7 ,在这种情况下你正在“分离”它们。

虽然这意味着原则上您可以使用静态类字段 MyClass.Values以及实例字段 xyz.Values由于具有相同的名称,因此通常不鼓励这样做,因为正是这种困惑。

作为单独的注释,您可以考虑注释 data方法为@staticmethod (并删除移动中的 self 参数)并将其称为 MyClass.data()为了更清楚地表明您将在每次调用时返回相同的列表实例。

关于Python - 静态类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43186844/

相关文章:

php - protected 静态成员变量

Python 3 - 托管服务器

python - 多维 NumPy 数组中的轴

python - opencv python connectedComponents 选择每个标签的组件

android - 如何通过单击 libgdx 上的按钮打开另一个类? (android开发eclipse)

php - 自定义 mysqli 准备函数

c - 系统如何识别不同函数中同名的静态变量?

python - Matplotlib 3D 散点动画

ruby - 在 Ruby 中,使用 "def initialize ( value = ' ') 初始化类实例有什么好处?

objective-c - NS_INLINE 相对于静态内联的优势是什么?