2013-02-12 71 views
0

比方说,我有这样的代码:调用构造函数没有赋值;实例后

models.py:

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

mymodule.py:

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

main.py

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

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

想法是稍后实例化Square。

谢谢!

+0

main.py中'models'从哪里来的? – martineau 2013-02-12 22:48:06

+0

@martineau只是一些python列表。 – user1491915 2013-02-12 22:59:00

+0

好的,因为你在mymodule.py中有'from models ...'而且你的main.py中没有定义它, – martineau 2013-02-12 23:29:36

回答

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呼叫它,部分将适用于已经通过了论证,并创建实例:

instance = somevariable() # calls Square('hello', 'there') 
+0

虽然这不仅仅是引用这个类吗?我会有兴趣用最初给出的论据来实例化它。 – user1491915 2013-02-12 22:59:16

+0

尽管名称和价值从何而来? 我想使用我在mymodule.py(特定的调用)中传递的'hello'和'there'。 – user1491915 2013-02-12 23:02:14

+0

对不起,我误解了你的问题;重读导致一个*不同的*答案.. – 2013-02-12 23:04:24

0

其实你在mymodule.py实例化它,但会被丢弃。为了避免这种情况,您需要将在那里创建的Square存储在名称中,否则它将被垃圾回收,因为没有任何内容引用它。这就是我的意思是:

mymodule.py:

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

然后你就可以直接,更快速地访问使用该名称在main.py这样的:

为主。PY

models = [] 
mod = __import__('mymodule') 
models.append(vars(mod)['a_square']) # access it by name 
0

“我们的想法是以后实例化广场”。

您可以通过存储可调用对象及其参数来实现。

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]) 

或者,如果你想获得超看中,并产生了很多的模型,你可以做一个列表:

models.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 

mymodule.py:

import models 
my_models = (
    (models.Square, ('hello', 'there'), {}), 
    (models.Round, ('goodbye', 'there'), {'otherstuff':'stuff'}) 
) 

main.py

m = __import__('mymodule') 
models = [model[0](*model[1], **model[2]) for model in m.my_models]