【问题标题】:"self" is lost when using a decorator使用装饰器时“自我”丢失
【发布时间】:2020-03-27 09:15:13
【问题描述】:

我正在尝试为基于插件的 IRC 机器人实现一个装饰器。

根据函数名称添加命令(“!command arg1 arg2”)应如下所示:

class CorePlugin:
    @BotCommand
    def mycommand(self, arguments):
        self.bot.privmsg("#mychannel", "invoked !mycommand %s" % " ".join(arguments))

装饰器如下所示:

class BotCommand:
    def __init__(self, func):
        events.add(func.__name__, func)

添加命令可以正常工作。 这是我的Events 班级:

class Events:
    def __init__(self):
        self.events = {}

    def add(self, cmd, func):
        self.events[cmd] = func

    def call(self, cmd, args):
        for c, f in self.events.items():
            if c == cmd:
                f(None, args)

Events.call 在 PRIVMSG 进入后在我的 Bot 类中被成功调用,但我需要手动将实际对象(CorePlugin)传递给我的装饰函数。目前它只是Nonefunc.__self__ 在这个过程中不知何故丢失了。

你知道如何解决这个问题吗?

【问题讨论】:

  • Events.call 在消息到达某处时被调用?究竟是什么调用了它?

标签: python-3.x decorator


【解决方案1】:

忘记装饰器
在这里,它比帮助更令人讨厌

__init__方法中CorePlugin
BotCommand(self.mycommand)

第一种解决方案的问题是BotCommandCorePlugin 之前初始化,
所以self 不存在。

这种方式函数mycommand“记住”它应该以CorePlugin对象作为第一个参数调用

注意
我不得不删除我的其他解决方案,因为它不起作用
BotCommand 类中制作 __call__ 方法不起作用
即使它是可调用的,它也不会自动获取 CorePlugin 对象作为参数
这仅发生在函数上(不能被继承)

【讨论】:

    猜你喜欢
    • 2020-04-12
    • 2012-07-25
    • 2021-04-03
    • 1970-01-01
    • 2011-07-03
    • 2015-03-21
    • 2021-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多