我使用 2 python 类作为配置文件。其中一个包含旧参数(不推荐使用),如果使用了不推荐使用的参数,我想显示一条消息。
这是我如何使用不同的类:
config_backup.py
class _ConfigBackup:
PARAM1 = 'a'
PARAM2 = 'b'
Run Code Online (Sandbox Code Playgroud)
config_new.py
class Config(_ConfigBackup):
PARAM3 = 'c'
PARAM4 = 'd'
cfg = Config
Run Code Online (Sandbox Code Playgroud)
然后我可以调用 cfg 并得到如下结果:
>>> cfg.PARAM3
'c'
>>> cfg.PARAM1
Parameter PARAM1 is deprecated.
'a'
Run Code Online (Sandbox Code Playgroud)
我认为函数或方法看起来像这样:
def warning(param):
print(f"Parameter {param.__name__} is deprecated.")
return param
Run Code Online (Sandbox Code Playgroud)
我不确定这是否可行,也许通过使用装饰器或 with 语句,知道吗?
您可以与@property
装饰器一起使用的一种方法
class Config(_ConfigBackup):
PARAM3 = 'c'
PARAM4 = 'd'
__PARAM1 = _ConfigBackup.PARAM1
@property
def PARAM1(self):
print(f"Parameter PARAM1 is deprecated.")
return Config.__PARAM1
cfg = Config()
print(cfg.PARAM1)
print(cfg.PARAM2)
print(cfg.PARAM3)
print(cfg.PARAM4)
Run Code Online (Sandbox Code Playgroud)
输出:
Parameter PARAM1 is deprecated.
a
b
c
d
Run Code Online (Sandbox Code Playgroud)
编辑:
另一种选择是修改__getattribute__
:
class Config(_ConfigBackup):
PARAM3 = 'c'
PARAM4 = 'd'
DEPRECATED = ['PARAM1', 'PARAM2']
def __getattribute__(self, item):
if not item == 'DEPRECATED' and item in Config.DEPRECATED:
print(f"Parameter {item} is deprecated.")
return object.__getattribute__(self,item)
Run Code Online (Sandbox Code Playgroud)
这是一个概念验证解决方案,它满足了由于属性太多而无法实现的反对意见。
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'
Run Code Online (Sandbox Code Playgroud)
我没有将已弃用的参数放在单独的类中,因为这会使示例不必要地复杂化。现实世界的代码需要能够处理命名不存在的参数的尝试,而不是这样做:
>>> 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'
Run Code Online (Sandbox Code Playgroud)