I have a class with about 200 stub functions, they look something like this:
def name1(self, **kwargs):
return self.run('name-1', kwargs)
def name2(self, ** kwargs):
return self.run('name-2', kwargs)
Run Code Online (Sandbox Code Playgroud)
So on and so forth.
There is a run function that takes care of the real work.
I want to reduce the 200 stub function to just 1 dynamic function that gets called when you make a call to the class with a method name that doesn't exist.
How do I do this?
您可以__getattr__在类中使用返回包装函数的方法run。您只需要一种在方法名称(例如name1)和应该传递给方法的字符串run(例如"name-1")之间进行转换的方法。如果没有任何改变的话,这当然是最简单的。这是一个使用字典进行翻译的快速实现。如果您需要它适用于许多名称,您可能需要使用字符串操作和正则表达式来完成。
name_translation_dict = {"name1": "name-1", "name2": "name-2"}
def __getattr__(self, name):
if name not in self.name_translation_dict:
raise AttributeError()
translated_name = self.name_translation_dict[name]
def method(**kwargs):
return self.run(translated_name, kwargs)
return method
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
565 次 |
| 最近记录: |