首页 > 解决方案 > Python 重构 - 多个类中的冗余函数

问题描述

这是我的代码,但显然这是多余的,因为我需要将例如 func4 添加到Contextand的两个地方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)

标签: python

解决方案


我的想法是定义一个方法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不存在的方法。


推荐阅读