Skip to content

Instantly share code, notes, and snippets.

@applenob
Last active September 11, 2020 06:06
Show Gist options
  • Save applenob/152730a40474531a6a4be2c7ff145179 to your computer and use it in GitHub Desktop.
Save applenob/152730a40474531a6a4be2c7ff145179 to your computer and use it in GitHub Desktop.
动态替换模型的少量filed或method
class ModelWrapper(object):
"""
在原始模型之外进行一层外包封装。
动态地替换原模型的属性。
"""
def __init__(self, execute_model):
self.execute_model = execute_model # 实际运行的模型
self.overwrite_model_attr()
def overwrite_model_attr(self):
"""模型优先使用wrapper模型的方法"""
attr_names = [attr_name for attr_name in dir(self)
if not attr_name.startswith("__")]
# print(attr_names)
for attr_name in attr_names:
if hasattr(self.execute_model, attr_name):
print(f"overwrite {attr_name} for original model {self.execute_model}")
setattr(self.execute_model, attr_name, getattr(self, attr_name))
def __getattr__(self, item):
"""若wrapper没有覆盖某属性,使用原模型的属性"""
if hasattr(self.execute_model, item):
return getattr(self.execute_model, item)
else:
raise AttributeError(f"{self} has not attribute {item} !")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment