0

假设我有这个代码:

模型.py:

class Square:
  def __init__(self, name, value):
    self._name = name
    self._value = value

mymodule.py :

from models import Square
Square('hello', 'there')

主文件

m = __import__('mymodule')
for i in dir(m):
  if i == 'Square':
     models.append(getattr(m, i))

我的问题是:我如何实例化我附加的 Square(当然是我在 mymodule.py 中给出的参数)?

这个想法是稍后实例化 Square。

谢谢!

4

3 回答 3

2

你的mymodule.py文件有缺陷;你从不存储实例。将其存储在变量中:

somevariable = Square('hello', 'there')

您不能只调用构造函数并让它悬空。

循环mymodule查找命名的属性Square不会得到你想要的,你会找到类引用,而不是实例。

也许您应该寻找该Square类型的对象:

from models import Square

for value in vars(m).itervalues():
    if isinstance(value, Square):
         models.append(value)

如果您想避免必须导入Square类,则必须测试类型名称,这更脆弱:

for value in vars(m).itervalues():
    if getattr(type(value), '__name__', None) == 'Square':
         models.append(value)

如果您想真正推迟构建,请稍后使用一组预设值构建它,请使用functools.partial()

from models import Square
from functools import partial

somevariable = partial(Square, 'hello', 'there')

如果您现在导入somevariable调用它,partial 将应用已经传入的参数并创建实例:

instance = somevariable()  # calls Square('hello', 'there')
于 2013-02-12T22:39:24.877 回答
0

实际上你在 mymodule.py 中实例化它,但它被丢弃了。为了阻止这种情况,您需要将Square创建的内容存储在具有名称的东西中,否则它将被垃圾收集,因为没有任何东西引用它。这就是我的意思:

mymodule.py :

from models import Square
a_square = Square('hello', 'there') # name it

然后,您可以在 main.py 中使用该名称直接更快地访问它,如下所示:

主文件

models = []
mod = __import__('mymodule')
models.append(vars(mod)['a_square'])  # access it by name
于 2013-02-12T23:27:34.770 回答
0

“这个想法是稍后实例化 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]
于 2013-02-13T00:15:03.870 回答