When I let a script do some processing, I usually go out of the config file, aggregate the setting values there, and when I execute it, I load that config and execute the processing. Among the setting values, there were times when I wanted to execute a certain process in a specific class. What should I do in such a case? Would you like to write parameters such as numerical values and generate classes by dividing them by if in the code, for example, ClassA for 1 and ClassB for 2? If you need a new Class C pattern, you have to add the if part of the code. In python, you can use globals () to create a class object from a string, which is convenient in such cases.
(update) As mentioned in the comment, the eval function can also create a class object from a string.
globals() This can be achieved using the globals () function. globals () returns a dictionary of currently loaded modules. You can use this to generate a class from a string.
This is a sample code.
parent_child.py
#Parent class
class Parent(object):
def __init__(self):
pass
def call(self):
print("I am parent.")
#Child class 1
class ChildAsBrother(Parent):
def __init__(self):
super().__init__()
def call(self):
print("I am child as brother.")
#Child class 2
class ChildAsSister(Parent):
def __init__(self):
super().__init__()
def call(self):
print("I am child as sister.")
#Normal object creation and calling
obj = Parent()
obj.call()
obj = ChildAsBrother()
obj.call()
# globals()Object generation using
obj = globals()["ChildAsSister"]() # <---Objects can be created from strings
obj.call()
#add to
#Method using eval
obj = eval("ChildAsSister")()
obj.call()
obj = eval("ChildAsSister()")
obj.call()
The execution result will be like this.
I am parent.
I am child as brother.
I am child as sister.
I am child as sister.
I am child as sister.
This way you can specify the class name you want to use in the config file and use it directly in your code. It's convenient
What exactly does globals () return in the first place? I checked it for a moment. I will introduce it here for your reference.
print(globals())
#Actually, it is displayed on one line, but it is hard to see, so it is broken.
{'__name__': '__main__',
'__doc__': None,
'__package__': None,
'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0xffdc5c90>,
'__spec__': None,
'__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>,
'__file__': 'parent_child.py',
'__cached__': None,
'Parent': <class '__main__.Parent'>,
'ChildAsBrother': <class '__main__.ChildAsBrother'>,
'ChildAsSister': <class '__main__.ChildAsSister'>,
'obj': <__main__.ChildAsSister object at 0xffd18b90>}
I don't know the details, but it seems that metadata and classes and objects in the execution environment are managed. It seems that the class in it is running.
Recommended Posts