【发布时间】:2023-03-22 06:53:01
【问题描述】:
我知道类是元类的实例,__new__ 在__init__ 之前运行,因为您必须在初始化之前创建一个实例。
现在想象一下:
import time
class ConfigurationsMeta(type):
def __new__(cls, name, bases, attr):
# Potentially a long task here (eg: Getting value from a web service)
time.sleep(2)
# Which class inherit from me (debug)
print(f'Class {name}')
config = super().__new__(cls, name, bases, attr)
#Set a variable to be propagated (Variable coming from web service)
setattr(config, "URL", "https://stackoverflow.com/")
return config
class Foo(metaclass=ConfigurationsMeta):
def __init__(self):
print(f'{__class__.__name__} : {self.URL}')
class Bar(Foo):
def __init__(self):
print(f'{__class__.__name__} : {self.URL}')
class Baz(Bar):
def __init__(self):
print(f'{__class__.__name__} : {self.URL}')
e = Foo()
s = Bar()
c = Baz()
-
很好,因为 URL 像我一样传播得很好
Foo : https://stackoverflow.com/ Bar : https://stackoverflow.com/ Baz : https://stackoverflow.com/ -
我现在确实有一些我不太了解的东西:
Class Foo在 2 秒后写入Class Bar在 2 秒后写入Class Baz在 2 秒后终于写入
所以元类被执行了 3 次。
这必须说明,由于__new__负责创建类,所以每次都要运行,所以3次。
我说的对吗?
我怎样才能避免它并让它只运行一次?
【问题讨论】:
-
__new__不应从 Web 服务中获取值... -
我说的对吗? - 是的。我怎样才能避免它并让它只运行一次? - 只有一个类的元类是
ConfigurationsMeta(或使用缓存)