静态类成员python [英] Static class members python

查看:29
本文介绍了静态类成员python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我使用静态类成员,以便我可以在类方法和同一类的静态方法之间共享数据(该类只会有 1 个实例化).我理解这很好,但我只是想知道静态成员何时初始化?是进口的吗?关于第一次使用类?因为我将要从 1 个以上的模块(因此超过 1 个导入语句)调用此类的静态成员.访问静态方法的所有模块是否共享相同的静态数据成员?如果我的主客户端删除了我的类的实例,然后重新创建它(没有完全终止或重新导入内容),我的数据成员会被保留吗?

So I'm using static class members so I can share data between class methods and static methods of the same class (there will only be 1 instantiation of the class). I understand this fine, but I'm just wondering when the static members get initialized? Is it on import? On the first use of the class? Because I'm going to be calling the static members of this class from more than 1 module (therefore more than 1 import statement). Will all the modules accessing the static methods share the same static data members? And if my main client deletes the instance of my class, and then recreates it (without terminating altogether or re-importing stuff), will my data members be preserved?

推荐答案

它们将在类定义时初始化,如果您将类作为模块的一部分导入,这将在导入时进行.这假设静态"类成员定义样式如下:

They will be initialized at class definition time, which will happen at import time if you are importing the class as part of a module. This assuming a "static" class member definition style like this:

class Foo:
    bar = 1

print Foo.bar # prints '1'

请注意,这是一个静态类成员,无需实例化该类.

Note that, this being a static class member, there is no need to instantiate the class.

import 语句将只执行一次模块的内容,无论执行多少次或在哪里执行.

The import statement will execute the contents of a module exactly once, no matter how many times or where it is executed.

是的,静态成员将由访问它们的任何代码共享.

Yes, the static members will be shared by any code accessing them.

是的,如果删除一个类的类型的对象,则该类的静态成员将被保留:

Yes, the static members of a class will be preserved if you delete an object whose type is that class:

# Create static member
class Foo:
    bar = 1

# Create and destroy object of type Foo
foo = Foo()
del foo

# Check that static members survive
print Foo.bar # Still prints '1'

这篇关于静态类成员python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆