Python 类而不是实例构造函数
有一个类似的问题,但它没有明确回答我的问题: 有没有一种方法可以让init/constructor函数在所有类实例中自动调用一次,以便初始化类变量Python 类而不是实例构造函数,python,Python,有一个类似的问题,但它没有明确回答我的问题: 有没有一种方法可以让init/constructor函数在所有类实例中自动调用一次,以便初始化类变量 class A: _config = None #load the config once for all instances @classmethod def contstructor(cls): cls._config = configparser.ConfigParser() cls._config.read("co
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")
这就是所谓的。它确实假设缓存可以作为布尔值进行计算
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()
这就是所谓的。它确实假设缓存可以作为布尔值进行计算
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在解析类时执行类定义中不属于方法的所有代码。因此,您可以直接在那里执行操作和赋值,也可以从那里调用类的自定义方法作为类构造函数
print("Now defining class 'A'...")
class A:
# define any initialization method here, name is irrelevant:
def __my_class_constructor():
print("--> class initialized!")
# this is the normal constructor, just to compare:
def __init__(self):
print("--> instance created!")
# do whatever you want to initialize the class (e.g. call our method from above)
__my_class_constructor()
print("Now creating an instance object 'a' of class 'A'...")
a = A()
输出将是:
Now defining class 'A'...
--> class initialized!
Now creating an instance object 'a' of class 'A'...
--> instance created!
类构造函数没有神奇的方法,但是Python在解析类时执行类定义中不属于方法的所有代码。因此,您可以直接在那里执行操作和赋值,也可以从那里调用类的自定义方法作为类构造函数
print("Now defining class 'A'...")
class A:
# define any initialization method here, name is irrelevant:
def __my_class_constructor():
print("--> class initialized!")
# this is the normal constructor, just to compare:
def __init__(self):
print("--> instance created!")
# do whatever you want to initialize the class (e.g. call our method from above)
__my_class_constructor()
print("Now creating an instance object 'a' of class 'A'...")
a = A()
输出将是:
Now defining class 'A'...
--> class initialized!
Now creating an instance object 'a' of class 'A'...
--> instance created!
你可以只检查cls.\u config是否为None,或者查看元类,或者只执行class A:\u config=some\u config\u parser。你可以只检查cls.\u config是否为None,或者查看元类,或者只执行class A:\u config=some\u config\u parser。这看起来正是我的意思,但我怀疑从风格的角度来看这是否很好?当包含在许多模块中时,它是否只执行一次?一个模块在Python进程中只导入一次。后续的导入调用将返回缓存的模块,而无需再次加载和计算它,因此该类也不会被解析两次。看,这看起来正是我的意思,但我怀疑从风格的角度来看,这是否很好?当包含在许多模块中时,它是否只执行一次?一个模块在Python进程中只导入一次。后续的导入调用将返回缓存的模块,而无需再次加载和计算它,因此该类也不会被解析两次。看见