在类中定义装饰器,这在类定义中也很有用

2024-09-30 23:31:51 发布

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

我试图在Python中将“子命令”系统实现为可继承类。我预期的用例是这样的:

^{1}$

我将Command.subcommand实现为一个静态方法,一切都很好,直到我试图向父类添加一个子命令,我得到了TypeError: 'staticmethod' object is not callable。事后看来,this显然行不通:

^{pr2}$

到目前为止,我发现的唯一替代方法是在父类之外声明subcommand修饰符,然后在类定义完成后注入它。在

def subcommand(method):
    method.is_subcommand = True

    return method

class Command(object):
    @subcommand
    def common(self):
        print "this subcommand is available to all child classes"

Command.subcommand = staticmethod(subcommand)
del subcommand

然而,作为一个在添加装饰器之前从未使用过Python的人,我觉得这很笨拙。有没有更优雅的方法来完成这一点?在


Tags: 方法命令objectis系统defthis用例
1条回答
网友
1楼 · 发布于 2024-09-30 23:31:51

我可以想出两种解决这个问题的办法。最简单的方法是在父类中使用完它之后,使它成为一个静态方法:

class Command(object):
    def subcommand(method): # Regular function in class definition scope.
        method.is_subcommand = True

        return method

    @subcommand
    def common(self):
        print "this subcommand is available to all child classes"

    subcommand = staticmethod(subcommand)
    # Now a static method. Can no longer be called during class definition phase.

这有点脆弱,因为在将它变成静态方法之后,不能在父类中使用它。更可靠的方法是添加一个中间类:

^{pr2}$

现在可以从CommandBase而不是{}继承所有类。在

相关问题 更多 >