【问题标题】:How to define a function where it doesn't matter whether you call the class如何定义一个函数,不管你是否调用类
【发布时间】:2021-04-24 16:53:27
【问题描述】:

我正在写一个类似于下面短程序的程序:

class Class():
 def __init__(self):
  pass
 def foo():
  pass

每当我将foo 称为Class.foo() 时,foo 中的所有内容都可以正常工作。

然而,当我将其称为Class().foo() 时,我得到一个错误:通过调用Class 我给foo 一个额外的参数,self.
如果我将参数self 添加到foo,那么如果我将函数调用为Class.foo(),它将不起作用。

我怎样才能避免这种情况?任何帮助将不胜感激:)

【问题讨论】:

  • 那是哪种编程语言?请添加适当的标签。另外,如果您知道可以以一种方式调用该方法,而不能以另一种方式调用该方法,那么为什么不简单地使用工作方式呢?
  • @NicoHaase 它的 python 抱歉我添加了标签
  • 似乎相关:Static methods in Python?

标签: python function class call


【解决方案1】:

看起来foo 应该是staticmethod

class Class:
    @staticmethod
    def foo():
        pass

print(Class.foo())  # -> None
print(Class().foo())  # -> None

附注如果需要,我可以对此进行扩展。这个问题有点模糊。

【讨论】:

  • 谢谢!我没想到会有一个装饰器...... :)
猜你喜欢
  • 1970-01-01
  • 2015-11-05
  • 2022-01-10
  • 2020-12-27
  • 2022-07-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多