实际上,这不是推荐的方法,而且我从未见过它在实际代码中使用过。
推荐的方法是使用模块,因为模块已经具有“全局”命名空间(有关 globals()、locals() 和 vars() 的更多信息,请参阅 this answer)。
但是,为了便于理解:
到目前为止,您所拥有的只是实例级别的共享状态的基本框架。您现在需要的是您要跟踪的其余状态:
class Config(Borg):
def __init__(self, config_file):
super(Config, self).__init__()
# load and parse file, saving settings to `self`
此方法的一个缺点是您可以有多个实例消耗内存,它们都知道相同的事情。 (内存不多,真的。)
另一种实现“共享状态”的方法是只创建一个实例,然后让类始终返回同一个实例——也称为singleton。
class Config(object):
the_one = None
def __new__(cls, config):
if cls.the_one is None:
cls.the_one = Super(Config, cls).__new__(cls)
# load and parse file, saving settings to `cls.the_one`
return cls.the_one
任何一种方法都会导致以下结果:
>>> config = Config('my_config_file.cfg')
>>> config.screen_size
# whatever was saved during the loading and parsing of the config file
# for 'screen_size'