Reputation: 33628
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!
Upvotes: 2
Views: 16631
Reputation: 95682
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)
Upvotes: 11
Reputation: 48577
Sort of. Thare are fancier ways, but I suggest this one.
def create_blah(class_type = "first", x=x1, y=y1, z=z1):
if class_type == "first":
instance=different_classes.first(x,y,z)
...
Upvotes: -1
Reputation: 34408
def create_blah(class_type = "first", x=x1, y=y1, z=z1):
class_ = different_classes.__dict__.get(class_type, None)
if isinstance(class_, type):
instance = class_(x, y, z)
You could also pass around the class object: class_ = different_classes.first
.
Upvotes: 0