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
.
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.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With