Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to instantiate class by it's string name in Python from CURRENT file? [duplicate]

Suppose I have myfile.py with some classes A, B and C defined INSIDE it. Now I want to instantiate class by it's name in str. I don't understand what to pass to getattr in order to do this. All examples like this assume that classes are in other module:

module = __import__(module_name)
class_ = getattr(module, class_name)
instance = class_()

but I don't have module_name.

like image 205
Dims Avatar asked Jul 02 '18 19:07

Dims


People also ask

How do you call the __ str __ method?

Python __str__() This method returns the string representation of the object. This method is called when print() or str() function is invoked on an object. This method must return the String object.

How do you call a function from its name stored in a string in Python?

Use getattr() to call a class method by its name as a string Call getattr(object, name) using a method name in string form as name and its class as object . Assign the result to a variable, and use it to call the method with an instance of the class as an argument.

How do I find the instance name of an object in Python?

Using attribute __name__ with type() , you can get the class name of an instance/object as shown in the example above. type() gives the class of object v and __name__ gives the class name.


1 Answers

If you are on the same module they are defined you can call globals(), and simply use the class name as key on the returned dictionary:

Ex. mymodule.py

class A: ...
class B: ...
class C: ...

def factory(classname):
    cls = globals()[classname]
    return cls()

Above solution will also work if you are importing class from another file

Otherwise, you can simply import the module itself inside your functions, and use getattr (the advantage of this is that you can refactor this factory function to any other module with no changes):

def factory(classname):
     from myproject import mymodule
     cls = getattr(mymodule, classname)
     return cls()
like image 171
jsbueno Avatar answered Oct 03 '22 05:10

jsbueno