2016-08-16 72 views
0

看起來很簡單,但我找不到解決方案。Python外部類

我用最簡單的例子來展示下面的問題。

(我的班安靜更復雜;))

文件A.py

import os, sys 
import B 
from B import * 
class _A(): 
    def __init__(self,someVars): 
     self.someVars = someVars 
    def run(self): 
     print self.someVars 

someVars = 'jdoe' 
B._B(someVars) 

文件B.py不進口匹配A

import A 
from A import _A 
class _B(): 
    def __init__(self,someVars): 
     self.someVars = someVars 
    def run(self): 
     A._A(self.someVars) 

import A - >回調:找不到_A

它只能當我這樣做 -

from A import * 

但是並在邏輯上的功能被執行2次。

感謝所有

+0

它因爲導入A不導入下劃線的類。你在調用'A._A'而不是'_A'時,你可以直接調用'_A'。切勿使用'from A import *',總是使用'import A'或'from A_A'。你也不需要兩個,一個會做。 [Underscored Class imports](http://stackoverflow.com/questions/551038/private-implementation-class-in-python)。 [導入與導入](http://stackoverflow.com/questions/710551/import-module-or-from-module-import) –

回答

0

沒有必要先import X,然後from X import Y。如果你需要Y(即使Y*),只需要from X import Y。這可能是2次執行的原因。

此外,爲什麼模塊之間存在循環依賴關係A -> B, B -> A?也許他們應該在一個文件呢?

0

由於循環依賴的,你所面臨的導入錯誤,你可以繼續你的工作爲:

文件A.py:

import os, sys 
#Below two import lines does cyclic dependency between file A and B which is wrong and will give import error, 
#commenting below two lines will resolve your import error 
#import B 
#from B import * 
class _A(): 
    def __init__(self,someVars): 
     self.someVars = someVars 
    def run(self): 
     print self.someVars 

someVars = 'jdoe' 
#B._B(someVars) #comment and respective logic should be moved in B file 

此外,您應該使用import Afrom A import _A和如果你使用的是以後你應該直接調用這個類作爲:_A(self.someVars)不是:A._A(self.someVars),這個調用約定將用於以前的導入樣式(import A),爲了更好的理解類和模塊的外部使用,你可以參考呃下面的鏈接:https://docs.python.org/3/tutorial/modules.html