简体   繁体   English

python:初始化class个成员

[英]python: initialize class members

I am using class to scope data (yap, maybe I should move this to a 2nd module).我正在使用 class 到 scope 数据(是的,也许我应该将其移至第二个模块)。 This class will contain a lot of "constants", however some of them need to be calculated when the script starts.这个 class 将包含很多“常量”,但是其中一些需要在脚本启动时计算。

It would be great if this static method would be run at startup, without me dealing with that.如果这个 static 方法在启动时运行,而不需要我处理,那就太好了。 Is there a function called at class creation?有没有在class创建时调用function? (not object creation!) (不是 object 创建!)

class Constants:
    data = {}
    capacity = 0
 
    def createData():
        data[1] = "123!"
        data[2] = "aaa"
        data[3] = "bb"
        for i in a: 
            capacity = capacity + len(i) 


#Constants.createData()
print(f"data[2] = {Constants.data[2]}")

Notes:笔记:

  1. The data is deterministic, and computed. data是确定性的,并且是经过计算的。 I could create a script that creates a python code... but this is ugly.我可以创建一个脚本来创建 python 代码……但这很难看。
  2. I will not instantiate this class, instead I am using it as a scope.我不会实例化这个 class,而是将其用作 scope。
  3. Note that capacity needs to be computer at runtime.请注意,容量需要在运行时由计算机计算。 In my real life application - data is much more randomized, and swapped.在我现实生活中的应用程序中——数据更加随机和交换。 I also have MIX/MAX values of arrays (again, arrays are populated at runtime, not "compile/write time"我还有 arrays 的 MIX/MAX 值(同样,arrays 在运行时填充,而不是“编译/写入时间”

Use class method for accessing class constants before initiating an instance:在启动实例之前使用 class 方法访问 class 常量:

look at this example:看这个例子:

class Test:
    var = 1

    @classmethod
    def fill(cls, value):
        cls.var = value

the result will be:结果将是:

In [3]: A.var
Out[3]: 1


In [4]: A.fill(2)
In [5]: A.var
Out[5]: 2

So, your code will be:所以,你的代码将是:

class Constants:
    data = {}
    capacity = 123
 
    @classmethod
    def createData(cls):
        cls.data['1'] = "123!"
        cls.data['2'] = "aaa"
        cls.data['3'] = "bb"

#Constants.createData()
print(f"data[2] = {Constants.data['2']}")

The code inside the class block is what's running at "startup". class块中的代码是在“启动”时运行的代码。 You can simply do anything you need to do in that code block, or even after it:您可以在该代码块中或什至之后简单地做任何您需要做的事情:

class Constants:
    data = {1: "123!"}    # define the data right here
    capacity = 123
 
    data[2] = "aaa"       # ... or here

Constants.data[3] = "bb"  # ... or here

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM