A memo I tried.
--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)
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'
classes.py
is used as it is.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