简体   繁体   English

python 调用 class 方法而不初始化 class

[英]python calling a class method without initializing the class

I want to call a function from a python class but it would be necessary to initialize it so is there a way to call class methods without initializing the class. I want to call a function from a python class but it would be necessary to initialize it so is there a way to call class methods without initializing the class. I have a js background I what I want is similar to this我有一个js背景我想要的和这个类似

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

You can use @staticmethod decorator to define static methods in python:您可以使用@staticmethod装饰器在 python 中定义 static 方法:

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

Class.method()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM