Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class as an input in a function

I have a file different_classes that contains three different classes. It is something like:

class first(object):
    def __init__(x, y, z):
    body of the first class

class second(first):
    def __init__(x, y, z, a=2, b=3):
    body of the second class

class third(object):
    def __init__(x, y, z):
    body of the third class

Now I have another file, say main.py where I want to be able to pass on the name of the class that needs to be called. For example, right now I do:

import different_classes
def create_blah():
    instance = different_classes.first()
    rest of the function body

when I want to use the first class in different_classes. If I want to use class second, I use different_classes.second().

Can I input the class name as an argument in the create_blah function. Something like:

def create_blah(class_type = "first", x=x1, y=y1, z=z1):
    instance = different_classes.class_type(x, y, z)

I know this may not be valid...but want to know if something similar can be done. Thanks!

like image 712
Curious2learn Avatar asked Jun 27 '26 07:06

Curious2learn


1 Answers

Rather than passing the name of the class, why not just pass the class itself:

def create_blah(class_type = different_classes.first, x=x1, y=y1, z=z1):
    instance = class_type(x, y, z)

Remember that a class is just an object like anything else in Python: you can assign them to variables and pass them around as arguments.

If you really do need to use the name, e.g. because you are reading it from a configuration file, then use getattr() to retrieve the actual class:

instance = getattr(different_classes, class_type)(x, y, z)
like image 116
Duncan Avatar answered Jun 28 '26 21:06

Duncan