Xavier Nodet
Xavier Nodet

Reputation: 5085

How can I give a class as argument to a Python function

I have two functions in my (first!) Python program that only differ by the class that must be instanciated.

def f(id):
    c = ClassA(id)
    ...
    return ...

def g(id):
    c = ClassB(id)
    ...
    return ...    

To avoid repeated code, I would like to be able to write a single function that would somehow accept the class to instanciate as a parameter.

def f(id):
    return f_helper(id, ... ClassA ...)

def g(id):
    return f_helper(id, ... ClassB ...)

def f_helper(id, the_class):
    c = ... the_class ... (id)
    ...
    return ...

I'm pretty sure this is possible, but did not find how...

Upvotes: 1

Views: 467

Answers (3)

Santa
Santa

Reputation: 11547

You can pass a callable to a function; a class itself is a callable, the returned object being an instance of said class.

def f_helper(id, the_class):
    c = the_class(id)
    # ...
    return # ...

Upvotes: 2

user395760
user395760

Reputation:

You pretty much got it right, just drop the dots. Classes are first-class values, you can just refer to them, as to any object. f would be return f_helper(id, ClassA) and g would be return f_helper(id, ClassB).

Upvotes: 4

Daniel DiPaolo
Daniel DiPaolo

Reputation: 56390

That works exactly as you have it (minus the ...s):

>>> class foo:
    pass

>>> def make_it(cls):
    return cls()

>>> make_it(foo)
<__main__.foo instance at 0x011D9B48>

This can be modified to take in/pass params to the class constructor as well if you like, but the idea is perfectly fine. Classes are first-class objects in Python.

Upvotes: 5

Related Questions