2017-04-12 4 views
0

dynamisch initialisiert wird. Ich verwende importlib & getattr, um eine Instanz einer Klasse dynamisch zu erstellen. Aber wenn ich Proxy.py ausführen, die unten zur Verfügung gestellt wird, wird der Konstruktor zweimal aufgerufen und ich erhalte doppelte Ergebnisse. Danke im Voraus. (Python 3.6.1)Konstruktor wird zweimal aufgerufen, wenn die Klasse

Ergebnis

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

Antwort

1

Ihr Proxy-Modul wird zweimal importiert - einmal als __main__ (wenn Sie ausführen) und einmal als Proxy (wenn es von importiert wird).

Die Lösung ist einfach: Schutz, den Anruf zu Crunner() so ist es nur dann ausgeführt, wenn Proxy als Skript verwendet wird:

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

Thanks again @bruno Desthuilliers für die schnelle Lösung und die Klarstellung. –

Verwandte Themen