Create an instance of a predefined class from a string in Python

A memo I tried.

Premise

--Using Python3.5.2. --The file is as follows

.
├── main.py
└── classes.py

classes.py


class Hoge(object):

    def __init__(self):
        self.name = 'hoge'

    def get_name(self):
        print(self.name)

class Fuga(object):

    def __init__(self):
        self.name = 'fuga'

    def get_name(self):
        print(self.name)

Patterns that use globals

main.py


#Apart from here`from classes import *`But yes
from classes import Hoge
from classes import Fuga

cls = globals()['Hoge']
instance = cls()
instance.get_name()  #=> 'hoge'

cls = globals()['Fuga']
instance = cls()
instance.get_name()  #=> 'fuga'

Pattern using getattr

main.py


import classes

cls = getattr(classes, 'Hoge')
instance = cls()
instance.get_name()  #=> 'hoge'

cls = getattr(classes, 'Fuga')
instance = cls()
instance.get_name()  #=> 'fuga'

The target module of getattr (classes in this case) must include the class dynamically specified by the character string. In fact, I think that it is often divided into 1 class and 1 file, so it seems that it is not very practical. As one method only.

I think there are other ways, but is the practical pattern using globals?

Recommended Posts

Create an instance of a predefined class from a string in Python
How to create an instance of a particular class from dict using __new__ () in python
Generate a class from a string in Python
Create a datetime object from a string in Python (Python 3.3)
Create a random string in Python
Various ways to create an array of numbers from 1 to 10 in Python.
Insert an object inside a string in Python
I want to color a part of an Excel string in Python
Create a function in Python
Create a dictionary in Python
Don't take an instance of a Python exception class directly as an argument to the exception class!
Find out the apparent width of a string in python
Reference order of class variables and instance variables in "self. Class variables" in Python
Python: Create a dictionary from a list of keys and values
Python> Read from a multi-line string instead of a file> io.StringIO ()
Create a DI Container in Python
Django: Import a class from a string
Create a pandas Dataframe from a string.
Create a binary file in Python
Create a Kubernetes Operator in Python
How to quickly count the frequency of appearance of characters from a character string in Python?
Create an executable file (EXE) by PyInstaller in a hybrid environment (Nimporter) of Python + Nim
How to make a string into an array or an array into a string in Python
Format when passing a long string as an argument of python
Try to extract a character string from an image with Python3
How to get a string from a command line argument in python
How to create a heatmap with an arbitrary domain in Python
Get the formula in an excel file as a string in Python
I thought a Python class variable was an instance variable and died
Generate a first class collection in Python
Conversion of string <-> date (date, datetime) in Python
Create a Python function decorator with Class
Build a blockchain with Python ① Create a class
Display a list of alphabets in Python 3
Create a simple GUI app in Python
Create a JSON object mapper in Python
# 5 [python3] Extract characters from a character string
[python] Get a list of instance variables
Create a deb file from a python package
[GPS] Create a kml file in Python
A memorandum of python string deletion process
Test & Debug Tips: Create a file of the specified size in Python
Hit a method of a class instance with the Python Bottle Web API
The eval () function that calculates a string as an expression in python
Get a datetime instance at any time of the day in Python
[Python] [Word] [python-docx] Try to create a template of a word sentence in Python using python-docx
[Python] class, instance
Python class, instance
Edit Excel from Python to create a PivotTable
Create a Vim + Python test environment in 1 minute
Draw a graph of a quadratic function in Python
Create a GIF file using Pillow in Python
How to embed a variable in a python string
How to create a function object from a string
Create a C array from a Python> Excel sheet
[python] Create a list of various character types
Create an executable file in a scripting language
Get the caller of a function in Python
I want to create a window in Python
Create a standard normal distribution graph in Python
[Python pandas] Create an empty DataFrame from an existing DataFrame