作为函数集合的Python类

2024-05-15 00:26:33 发布

您现在位置:Python中文网/ 问答频道 /正文

所以这里有一个我目前所面临的情况的简化版本。在

我要上课。它做了很多事情,但我最关心的是每个类成员当前都接受一个静态函数库,并使用该库执行一系列命令。在

class Example:
    def __init__(self, commands, library, data):
        self.commands = commands
        self.library = library
        self.data = data

    def execute(self):
        for command in self.commands:
            result = getattr(self.library, command)(self)
            self.data[result[0]] = result[1]

我想拥有切换这些函数库的能力。当前的问题是,我正在构建的大多数库共享一些核心函数,而其他函数则不同或被重写。目前我使用一个类来表示这些库,因为类结构的自然继承为我处理一切。在

^{pr2}$

下面是已执行代码的示例。这很简单,所以可能不能很好地理解我的观点。我尝试构建的实际代码决定了通过用户输入执行的命令,基于数据库中不断变化的环境变量运行的数据集,然后有一些逻辑将它们分配到能够处理所有事情的适当函数库中。在

foo1 = Example(commands=['method_b', 'method_a'], library=Foo, data={'x': 3, 'y': 4})
foo2 = Example(commands=['method_b', 'method_a'], library=FooAlt1, data={'x': 3})
foo3 = Example(commands=['method_b', 'method_a'], library=FooAlt2, data={'x': 3})

foo1.execute()
foo2.execute()
foo3.execute()

print('RESULTS')
print('foo1: {}'.format(foo1.data))
print('foo2: {}'.format(foo2.data))
print('foo3: {}'.format(foo3.data))

# RESULTS
# foo1: {'z': 16, 'x': 12, 'y': 4}
# foo2: {'z': 15, 'x': 3, 'y': 12}
# foo3: {'z': 6, 'x': 3, 'y': 3}

这个方法对我来说很好,但是感觉非常不象python,因为我主要使用类作为函数的存储容器。但是,如果不使用类,我想不出一个好的方法来实现它。类结构使我更容易更新(我只需更改一个函数,继承该函数的所有内容也将受到影响),如果我要创建一个扩展或修改现有库的替代库,则可以轻松地继承函数。在

有没有更好的方法来达到我想要的结果,还是我一直在使用类?在


Tags: 函数selfformatexecutedataexamplelibraryresult

热门问题