python 您可以将类(不是对象)作为参数传递给python中的方法吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/850921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 20:59:05  来源:igfitidea点击:

Can you pass a class (not an object) as a parameter to a method in python?

pythonstaticparameters

提问by Jesse Shieh

I want to do something like the following

我想做以下事情

class A:
  def static_method_A():
    print "hello"

def main(param=A):
  param.static_method_A()

I want this to be equivalent to A.static_method(). Is this possible?

我希望这相当于A.static_method(). 这可能吗?

回答by Chris Jester-Young

Sure. Classes are first-class objects in Python.

当然。类是 Python 中的一流对象。

Although, in your example, you should use the @classmethod(class object as initial argument) or @staticmethod(no initial argument) decorator for your method.

尽管在您的示例中,您应该为您的方法使用@classmethod(类对象作为初始参数)或@staticmethod(无初始参数)装饰器。

回答by Greg Hewgill

You should be able to do the following (note the @staticmethoddecorator):

您应该能够执行以下操作(注意@staticmethod装饰器):

class A:
  @staticmethod
  def static_method_A():
    print "hello"
def main(param=A):
  param.static_method_A()

回答by Unknown

Sure why not? Don't forget to add @staticmethod to static methods.

当然为什么不呢?不要忘记将@staticmethod 添加到静态方法中。

class A:
  @staticmethod
  def static_method_A():
    print "hello"

def main(param=A):
  param.static_method_A()