【问题标题】:How to call method of function from class variable [duplicate]如何从类变量中调用函数方法[重复]
【发布时间】:2020-06-10 18:17:43
【问题描述】:

我有课

class Test(object):
    @staticmethod
    def f(str):
      print(str)
    a = f('aaa')

如何正确操作?我有'staticmethod' object is not callable 错误。 classmethod 属性也会出错。请不要建议课外打电话,我希望它以这种方式实现。

【问题讨论】:

标签: python


【解决方案1】:

来自documentation

它可以在类(例如 C.f())或实例(例如 C().f())上调用。该实例被忽略,除了它的类。

所以你需要在类中的另一个函数中调用它,或者从类中创建一个对象实例。 例如:

class Test(object):

    def __init__(self):
        self.a = self.f('aaa')

    @staticmethod
    def f(str):
      print(str)

【讨论】:

  • 请编辑您的答案,并附上代码 sn-p 的文字说明,并解释它是如何回答问题的
【解决方案2】:

要从类内部调用它,请使用 self 关键字。

a = self.f('aaa')

【讨论】:

  • self 在 Python 中不是关键字
【解决方案3】:
class Test(object):
   @staticmethod
   def f(str):
     print(str)
   a = f.__func__('aaa')

更多详情请参阅'staticmethod' object is not callable

【讨论】:

    猜你喜欢
    • 2012-02-10
    • 2022-11-26
    • 1970-01-01
    • 2020-04-15
    • 2015-10-25
    • 1970-01-01
    • 1970-01-01
    • 2019-03-29
    • 1970-01-01
    相关资源
    最近更新 更多