我正在使用2 python类作为配置文件。其中一个包含旧参数(不推荐使用),如果使用了不推荐使用的参数,我想显示一条消息。
这是我使用不同类的方法:
config_backup.py
class _ConfigBackup:
PARAM1 = 'a'
PARAM2 = 'b'
config_new.pyclass Config(_ConfigBackup):
PARAM3 = 'c'
PARAM4 = 'd'
cfg = Config
然后,我可以调用cfg并得到如下结果:>>> cfg.PARAM3
'c'
>>> cfg.PARAM1
Parameter PARAM1 is deprecated.
'a'
我认为功能或方法如下所示:def warning(param):
print(f"Parameter {param.__name__} is deprecated.")
return param
我不确定这是否可行,可能是通过使用decorator或with语句,有什么主意吗?
最佳答案
这是一个概念验证解决方案,它满足了具有太多无法使用的属性的目标。
class Config:
def __init__(self):
self.deprecated = {'PARAM1': 'a', 'PARAM2': 'b'}
self.nondeprecated = {'PARAM3': 'c', 'PARAM4': 'd'}
def __getattr__(self, parmname):
if parmname in self.__dict__["deprecated"]:
print(f"{parmname} is deprecated")
return self.__dict__["deprecated"][parmname]
return self.__dict__["nondeprecated"][parmname]
>>> c = Config()
>>> c.PARAM1
PARAM1 is deprecated
'a'
>>> c.PARAM2
PARAM2 is deprecated
'b'
>>> c.PARAM3
'c'
我没有将不推荐使用的参数放在单独的类中,因为这样会使示例不必要地复杂化。并且真实世界的代码将需要能够应付命名不存在的参数的尝试,并且不能这样做:>>> c.PARAM5
Traceback (most recent call last):
File "<pyshell#105>", line 1, in <module>
c.PARAM5
File "<pyshell#100>", line 9, in __getattr__
return self.__dict__["nondeprecated"][parmname]
KeyError: 'PARAM5'
关于python - 调用类变量时打印消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65614875/