“这个想法是稍后实例化 Square。”
您可以通过存储可调用对象及其参数来做到这一点。
import models
# save as (callable, args, keywords). This does not create a Square
my_model = (model.Squares, ('hello', 'there'), {})
# sometime later, create the square
my_square = my_model[0](*my_model[1], **my_model[2])
或者如果你想变得超级花哨并生成很多模型,你可以列出一个列表:
模型.py:
class Square(object):
def __init__(self, name, value):
self._name = name
self._value = value
class Round(object):
def __init__(self, name, value, otherstuff=None):
self._name = name
self._value = value
self._otherstuff = otherstuff
我的模块.py:
import models
my_models = (
(models.Square, ('hello', 'there'), {}),
(models.Round, ('goodbye', 'there'), {'otherstuff':'stuff'})
)
主文件
m = __import__('mymodule')
models = [model[0](*model[1], **model[2]) for model in m.my_models]