【问题标题】:Python decorator that is a method in a class which is in different modulePython 装饰器,它是位于不同模块中的类中的方法
【发布时间】:2018-08-10 05:44:02
【问题描述】:

我想使用一个装饰器,它是一个在不同 python 模块中的类中的函数。

在全局范围内创建类的实例并使用像“@global_obj.my_decor”这样的装饰器会起作用。

但我觉得它看起来不干净。还有其他方法吗?

【问题讨论】:

标签: python decorator python-decorators


【解决方案1】:

如果您只是想避免使用全局对象(我可能会想要),您总是可以避免使用语法糖并手动创建和对象并装饰您的函数:

In [23]: class Foo:
    ...:     def deco(self, f):
    ...:         def wrapper(*args, **kwargs):
    ...:             print("hi")
    ...:             result = f(*args, **kwargs)
    ...:             print("I am decorated")
    ...:             return result
    ...:         return wrapper
    ...:

In [24]: def func(x, y):
    ...:     return 2*x + 3*y
    ...:
    ...:

In [25]: func = Foo().deco(func)

In [26]: func(3,2)
hi
I am decorated
Out[26]: 12

对我来说,这表明你可能会在没有课程的情况下过得更好。但没有更多细节,我只能猜测。

【讨论】:

  • 缺少@staticmethod
  • @aydow 它不需要它。如果它静态方法,那么您可以使用@Foo.static_deco 语法糖。我假设 OP 实际上需要一个带状态的类。但是如果你要使用@staticmethod,为什么不只是一个普通的装饰器函数呢?
  • @juanpa.arrivillaga,谢谢。我只是避免使用装饰器。我在支持中间件的 python 中使用 Falcon API。我已将逻辑(实际上是 auth-token 验证)放在中间件中,因此每次调用我的实际 API 之前都会调用它。而且它只在一个地方编码
猜你喜欢
  • 2014-12-29
  • 2012-02-09
  • 2021-09-12
  • 2018-07-14
  • 2017-11-28
  • 2012-09-03
  • 2016-03-17
  • 2021-04-12
  • 1970-01-01
相关资源
最近更新 更多