Skip to main content
 首页 » 编程设计

python之Python 中的静态类变量,不会为每个实例复制

2025年05月04日56lhb25

我需要一种方法来在 Python 中创建一个只有类才有的静态类变量。我无法承受为每个实例一遍又一遍地创建这个变量,因为目标类变量将是一个巨大的只读数据结构。每个实例都必须能够在整个类中出于只读目的访问它,但是由于它是大量数据并且将有数千个实例,所以我无法承受每个实例将再次创建此数据结构的另一个副本。

我找到了 this question ,但这并没有解决我的问题,因为建议的静态类变量是为每个实例创建的:

>>> class MyClass(): 
    i = 1 
>>> m = MyClass() 
>>> m.i 
1 

换句话说,我正在寻找一个类似于 PHP 的静态类变量:

<?php 
class Foo 
{ 
    public static $my_static = 'foo'; 
} 
 
$foo = new Foo(); 
print $foo::$my_static . "\n";     // Accessable throught the class 
print $foo->my_static . "\n";      // Undefined "Property" my_static      
?> 

这正是我所需要的,静态类变量只为类创建一次,所有实例都可以通过类访问它,但是这个静态类变量不会为每个新实例一遍又一遍地创建。是否可以在 Python 中创建这样的静态类变量?

PS:如果我不使用 OOP,我现在有一些解决方法,但如果我能找到一个好的且清晰易读的 OOP 解决方案,那么它在整个项目中会更有意义。

请您参考如下方法:

the static class variable suggested is created for each instance

这是错误的,你可以很容易地证明:

>>> class Test(): 
    class_attr = [] 
 
 
>>> t1 = Test() 
>>> t2 = Test() 
>>> t1.class_attr is t2.class_attr 
True  # this means that they reference exactly the same object 
>>> t1.class_attr.append(1)  # alter via t1 
>>> t2.class_attr 
[1]  # see the changes via t2 

但是,您可以使用实例属性覆盖类属性:

>>> t1.class_attr = [] 
>>> t1.class_attr is t2.class_attr 
False 

因此,如果您需要替换类属性(而不是像append 那样就地更改它),您应该通过类而不是实例(在这种情况下,Test.class_attr = [] 会同时影响 t1 和 t2)。