【问题标题】:I am trying to write a decorator to test a command for call a function我正在尝试编写一个装饰器来测试调用函数的命令
【发布时间】:2021-11-16 19:13:42
【问题描述】:

在我看来,错误与_input 相关,但我不确定

import random
from functools import wraps

_input = input()

def name(command='help'):
    def _name(func):
        @wraps(func)
        def inner(*args, **kwargs):
            if _input == command:
                func(*args, **kwargs)

        return inner
    return _name


@name(command='test')
def poo():
    print('5')

@name(command='test_2')
def foo():
    print('Hello')
>>>test
5

(对不起我的英语)

【问题讨论】:

  • 您的代码中的wraps 是什么?
  • 它看起来像来自functoolswraps
  • 你指的错误是什么?
  • here they told@GhostOps
  • 那么问题是什么?

标签: python python-decorators


【解决方案1】:

我认为这里只是一个误解。你似乎认为如果你运行代码并输入test,它应该运行poo。 (呃,什么名字)。但它根本不会运行任何东西,因为脚本中唯一执行行是导入、_input = input() 和装饰器(因为装饰器是semantic sugar)。

如果您想在键入特定命令时运行 fn,请改用 fns 的 dict:

def poo:
    pass


fns = {"test":poo}

choice = None
while choice not in fns:
    choice = input("Fn: ")

fn[choice]()

请注意,您的代码没有其他问题,如果您尝试测试装饰器,则可以在最后添加对两个 fns 的调用,作为注释说明。

装饰器

由于对装饰器似乎存在一些分歧,以下是等价的:

@mydecorator(*args)
def fn():
    pass

mydecorator(*args)(fn)

也许这样可以更清楚地知道调用装饰器代码的位置。

【讨论】:

  • 你知道discord.py?我正在尝试写一些类似的东西(我希望你明白我的意思)
  • btw the only executed line 不是严格正确的,函数 name()_name() 都被调用了两次。
  • @quamrana ?你知道装饰器是什么吗?
  • @quamrana 是的,我说得不准确。我会更新答案。
  • @Lolo 我已经更新了显示装饰器的答案,我确实不准确,对不起!
【解决方案2】:

如果问题是:Why doesn't my program output 5,那么答案是:因为您没有调用任何函数。

这个特定问题的最简单的解决方案是调用函数并让你的装饰器进行它设计的过滤:

...
# code from the OP elided
poo()
foo()

输出:

test
5

【讨论】:

    猜你喜欢
    • 2014-09-20
    • 2012-11-05
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 2021-09-09
    • 2021-01-02
    • 2020-02-03
    • 1970-01-01
    相关资源
    最近更新 更多