有一个类似的问题,但没有明确回答我的问题:
有没有办法拥有一个init / constructor函数,该函数会在所有类实例中自动被调用一次,以便初始化类变量?
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”。它确实假定可以将“缓存”评估为布尔值。
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()
关于python - 类而不是实例构造函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36737639/