【问题标题】:python calling a class method without initializing the classpython调用类方法而不初始化类
【发布时间】:2022-01-17 23:08:33
【问题描述】:

我想从 python 类中调用一个函数,但有必要对其进行初始化,所以有没有一种方法可以在不初始化类的情况下调用类方法。我有一个js背景我想要的和这个类似

class foo {
  static calculate() {
    return 'bar';
  }
}

【问题讨论】:

  • @MisterMiyagi 大多数不熟悉 Python 的人使用“类方法”来指代属于某个类的方法(无论其类型如何),而不是专门的 classmethod

标签: python python-3.x class oop


【解决方案1】:

可以使用@staticmethod装饰器在python中定义静态方法:

class Class:
    @staticmethod
    def method():
        print("Method called")

Class.method()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-17
    • 1970-01-01
    • 2014-04-18
    • 1970-01-01
    • 2016-08-13
    • 2011-04-01
    相关资源
    最近更新 更多