2013-02-12 101 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] 
相關問題