2011-10-06 43 views
2

我有3個文件,文件1個文件進口2,文件2個進口文件3和文件3只需要REFFERENCE東西在文件1.這一個基本的例子是Python的進口父文件

#---------------------File1.py--------------------- 
import File2 

class core(): 
    def __init__(self): 
     self.something = "Hello World" 
     self.run = File2.run() 

c = core() 

#---------------------File2.py--------------------- 
import File3 

class run(): 
    def __init__(self): 
     self.somethingelse = "Cows" 
     File3.func() 

#---------------------File3.py--------------------- 
import File1 

class func(): 
    print File1.c.something 

所以你可以看到,File3需要訪問File1中存在的變量'c.something',該變量調用文件2的類的一部分,該文件2又調用文件3.

這是從一段代碼我有「 inhereted「,其餘的代碼相當複雜,所以我並不想要改變這些事情。爲了給出一個更現實的例子,下面是實際代碼的功能。

#---------------------File1.py--------------------- 
import File2 
import config 

class core(): 
    def __init__(self): 
     self.config = config.load() #Config.load is an expensive DB opperation, and should only be run once 
     self.run = File2.run() 

c = core() 

#---------------------File2.py--------------------- 
import File3 

class run(): 
    def __init__(self): 

     # 
     # Do some things that don't require access to 'config' 
     # 

     File3.func() 

#---------------------File3.py--------------------- 
import File1 

class func(): 
    #Do some stuff that requires access to the config 
    print File1.c.config['some config'] 

我們只能調用config.load()一次,但許多函數必須能夠訪問它。我們也不能通過self.config作爲函數調用的參數,因爲有太多的函數依賴於它是合理的。如果可能的話,我們希望避免使用全局變量並在類中保留它。

這是什麼最好的方法呢?

回答

6

我真的不想要改變。

(...)

什麼是去了解它的最好方法?

我不想打破這個給你,但最好辦法就是重構代碼;即混洗周圍的東西。你不需要循環依賴,從長遠來看,它們會讓你的生活變得艱難。分層(樹或DAG結構)模塊設置是最容易處理的。

實現此目的的最簡單方法是將三個模塊合併爲一個模塊,然後將某些內容移回到單獨的模塊中。

+0

不幸的是,3個模塊在我的例子,但200在實際的代碼,移動萬事成一個將是一場噩夢(更比它已經)保持 – Smudge

+0

@samarudge:不,移動*是您擔心的維護噩夢。之後,維護可能會變得更容易。解決這個問題的唯一方法就是必須記錄下來的黑客行爲。 –

1

你可以在運行時,而不是在模塊加載時導入,所以文件3將是:

class func(): 
    def __init__(self): 
     import File1 
     #Do some stuff that requires access to the config 
     print File1.c.config['some config'] 

雖然仍然有c = core()線的問題 - 這條線意味着所有額外的模塊初始化(發生在core())發生在它被分配給c變量之前。要解決這個問題也一樣,你可能希望有文件1爲這樣的事情:

import File2 

class core: 
    def __init__(self): 
     self.config = {} 

    def run(self): 
     self.run = File2.run() 

c = core() # make sure the global variables are initialised nicely 
c.run() # after initialisation is finished, *then* do the work