Python 中父子之间的共享变量

问题描述 投票:0回答:1

我有一个全局配置

pp
,它在运行时发生变化,并且需要在所有父/子对象之间共享它。

class Config: pp = 'Init' def __init__(self): pass class Child(Config): def __init__(self, name): self.cc = name par = Config() print(f"Parent: {par.pp}") par.pp = "123" print(f"Parent: {par.pp}") child = Child('XYZ') print(f"Child-1: {child.pp} - {child.cc}")
打印:

Parent: Init Parent: 123 Child-1: Init - XYZ
第三条线预计是

Child-1: 123 - XYZ


我怎样才能以干净的方式实现它?

更新* 目前它适用于以下方法:

class Config: pp = 'Init' def __init__(self): pass def set_pp(self, val): type(self).pp = val
    
python inheritance singleton
1个回答
0
投票
一种方法是通过将 getter 重新路由到父级的属性来完成此操作。 例如通过

class Config: pp = 'Init' class Child(Config): def __init__(self, name): self.cc = name @property def pp(self): return Config.pp @property.setter def pp(self, value): Config.pp = value
    
© www.soinside.com 2019 - 2024. All rights reserved.