2017-04-12 31 views
0

我正在使用importlib & getattr來動態創建一個類的實例。但是,當我運行下面提供的Proxy.py時,構造函數被調用兩次,並且我得到重複的結果。提前致謝。 (Python的3.6.1)構造函數在動態實例化類時被調用兩次

結果

inside Cproxy contructor 
inside Cproxy read() 
inside Cproxy contructor 
inside Cproxy read() 

Runner.py

import importlib 
class Crunner: 
    def __init__(self, nameofmodule, nameofclass):   
     self.run(nameofmodule, nameofclass) 

    def run(self, nameofmodule, nameofclass): 
     module = importlib.import_module(nameofmodule)    
     class_ = getattr(module, nameofclass) 
     instance = class_() 
     instance.read() 

Proxy.py

from Runner import Crunner 
class Cproxy: 
    def __init__(self): 
     print("inside Cproxy contructor")  
    def read(): 
     print("inside Cproxy read()") 


Crunner("Proxy", "Cproxy") 

回答

1

你的代理模塊導入兩次 - 一次爲__main__(當您運行python Proxy.py時)和一次爲Proxy(當它由Crunner導入時)。

解決方法很簡單:守衛調用Crunner()所以當Proxy作爲腳本它只是執行:

if __name__ == "__main__": 
    Crunner("Proxy", "Cproxy") 
+0

再次感謝@bruno desthuilliers爲迅速解決和澄清。 –

相關問題