cnikolaou
cnikolaou

Reputation: 3992

Python: passing a constant as method parameter

I want to pass a class name to a method as a constant.

Example:

def foo(Bar):
   # ...

Eventually, I want to be able to use Bar as a class name in method foo

Is this possible to do?

Upvotes: 1

Views: 2668

Answers (2)

mahendra kamble
mahendra kamble

Reputation: 1395

Check out this

class Bar():
    pass

def foo(param):
    print "class_name is {}".format(param.__name__) #prints class name

foo(Bar)

Upvotes: 0

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48047

Yes, you can pass class as an argument to function. Below is the example to prove it.

class Bar():
    @staticmethod   # created staticmethod; can be call without creating the object
    def my_print():
        print 'Hello, I am class function'

def foo(my_class):
    my_class().my_print()  # call my_print() of the object passed

foo(Bar) # Pass class "Bar" as argument to "foo()"
# prints: Hello, I am class function

Upvotes: 1

Related Questions