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…
That works exactly as you have it (minus the
...s):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.