Jesse Shieh
Jesse Shieh

Reputation: 4850

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

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?

Upvotes: 9

Views: 13822

Answers (3)

Greg Hewgill
Greg Hewgill

Reputation: 993393

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

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

Upvotes: 5

Unknown
Unknown

Reputation: 46791

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

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

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

Upvotes: 0

C. K. Young
C. K. Young

Reputation: 223083

Sure. Classes are first-class objects in Python.

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

Upvotes: 9

Related Questions