python - Python 重构 - 多个类中的冗余函数
问题描述
这是我的代码,但显然这是多余的,因为我需要将例如 func4 添加到Context
and的两个地方ContextManager
......有没有更好的方法来更优雅地编写它?
class Context(object):
def __init__(self, uuid):
self.uuid = uuid
def func1(self):
print("This is func1")
def func2(self, arg1):
print(arg1)
def func3(self, arg1, arg2, arg3):
print(arg1)
print(arg2)
print(arg3)
class ContextManager(object):
def __init__(self):
self.contexts_by_uuid = {}
def create_context(self):
ctx_uuid = uuid.uuid4()
self.contexts_by_uuid[ctx_uuid] = Context(ctx_uuid)
return ctx_uuid
def func1(self, ctx_uuid):
ctx = self.contexts_by_uuid.get(ctx_uuid)
return ctx.func1()
def func2(self, ctx_uuid, arg1):
ctx = self.contexts_by_uuid.get(ctx_uuid)
return ctx.func2(arg1)
def func3(self, ctx_uuid, arg1, arg2, arg3):
ctx = self.contexts_by_uuid.get(ctx_uuid)
return ctx.func2(arg1, arg2, arg3)
解决方案
我的想法是定义一个方法ContextManager
,用于通过名称getattr
访问该方法Context
,如下所示:
def func(self, func_name, ctx_uuid, *args):
ctx = self.contexts_by_uuid.get(ctx_uuid)
return getattr(ctx, func_name)(*args)
但是,我不建议这样做,因为它会牺牲可读性,并且无法进行任何静态检查以确保代码有效性。例如,您可以很容易地尝试访问一个Context
不存在的方法。
推荐阅读
- sql - 如何在sequelize中实现`join on and`?
- bash - 如何判断后台工作何时“完成”
- android - Kotlin 版本错误,即使项目中没有相关版本
- typo3 - Typo3 TCA 覆盖 tt_content 将调色板添加到现有选项卡 (--div--)
- java - java中的击打游戏
- amazon-web-services - 循环迭代中间的等待时间 AWS Step Function
- javascript - 数组文字中是否有动态索引的表示法?
- php - 如何将额外的变量传递给 typeahead.js
- java - Java根据条件添加到实例化列表中,否则实例化新列表
- python - 更简单的替代 np.where() 来更改行值 pandas