【问题标题】:TypeError: 'staticmethod' object is not callable while using decorators inside classesTypeError:在类中使用装饰器时,“staticmethod”对象不可调用
【发布时间】:2021-09-29 06:48:38
【问题描述】:

下面有一些代码

class Example:
    def __init__(self,height,weight)
        self.height = height
        self.weight = weight

    @staticmethod
    def some_op(func)
        def inner(*args,**kwargs)
        s = func(*args,**kwargs)
        print("Implementing function...")


    @some_op
    def num_op(self,values):
        for value in values:
            v = value * 10
            q = v - 100
            c = q ** -1
        return c

example = Example()

values = [11,23123,1209,234]

example.num_op(values)

但它输出:

TypeError: 'staticmethod' object is not callable

我真的不知道类中的装饰器,所以我应该如何更改代码以使其返回:

Implementing function...
0.0004464285714285714

非常感谢!

【问题讨论】:

    标签: python class error-handling static-methods python-decorators


    【解决方案1】:

    静态方法不可调用;它是一个对象,其__get__ 方法返回一个可调用对象。但是,您不是将some_op(不完整的定义放在一边)作为属性访问,而是作为常规函数访问,因此它的__get__ 方法永远不会被使用。你有两个选择:

    1. some_op 定义为类外的常规函数​​。
    2. 不要将some_op 定义为静态方法。由于您只是在类定义本身内部调用它,所以让它成为一个常规函数,并且不要将它用作实例方法。 (您可以将其定义为_some_op,以强调它不应该在课堂外使用。)

    有关__get__ 是什么以及它的工作原理的更多信息,请参阅Decriptor HowTo Guidestatic methods 部分。

    【讨论】:

      猜你喜欢
      • 2020-08-19
      • 2021-11-22
      • 2020-09-22
      • 2019-11-18
      • 2017-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-09
      相关资源
      最近更新 更多