有一个类似的问题,但没有明确回答我的问题: 有没有办法让初始化/构造函数在所有类实例中自动调用一次,以便初始化类变量?
class A:
_config = None
#load the config once for all instances
@classmethod
def contstructor(cls):
cls._config = configparser.ConfigParser()
cls._config.read("config_for_A.ini")
请您参考如下方法:
这称为“Orcish Maneuver”。它确实假设可以将“缓存”评估为 bool 值。
class A:
_config = False
#load the config once for all instances
@classmethod
def contstructor(cls):
cls._config = configparser.ConfigParser()
cls._config.read("config_for_A.ini")
def __init__(self):
self._config = self._config or self.contstructor()
hay = A()
bee = A()
sea = A()
