'python: initialize class members
I am using class to scope data (yap, maybe I should move this to a 2nd module). This class will contain a lot of "constants", however some of them need to be calculated when the script starts.
It would be great if this static method would be run at startup, without me dealing with that. Is there a function called at class creation? (not object creation!)
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:
- The
data
is deterministic, and computed. I could create a script that creates a python code... but this is ugly. - I will not instantiate this class, instead I am using it as a scope.
- 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"
Solution 1:[1]
Use class method for accessing class constants before initiating an instance:
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']}")
Solution 2:[2]
The code inside the class
block is what's running at "startup". 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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Mehrdad Pedramfar |
Solution 2 | deceze |