2010-11-27 33 views
1

我正在開發一個PyQT4應用程序,並且一次性瀏覽所有代碼變得非常困難。我知道import foo聲明,但我無法弄清楚如何讓它將代碼直接導入到我的腳本中,如BASH source foo聲明。用Python直接導入代碼到腳本中?

我試圖做到這一點:

# File 'functions.py' 

class foo(asd.fgh): 
    def __init__(self): 
    print 'foo' 

這裏是第二個文件。

# File 'main.py' 

import functions 

class foo(asd.fgh): 
    def qwerty(self): 
    print 'qwerty' 

我想從兩個單獨的文件中包含代碼或合併類減速。在PHP中,有import_once('foo.php'),正如我前面提到的,BASH有source 'foo.sh',但是我可以用Python來完成嗎?

謝謝!

回答

4

出於某種原因,我的第一個想法是多重繼承。但爲什麼不嘗試正常的繼承?

class foo(functions.foo): 
    # All of the methods that you want to add go here. 

是否有一些原因,這將無法正常工作?


既然你只是要合併類的定義,你爲什麼不這樣做:

# main.py 
import functions 

# All of the old stuff that was in main.foo is now in this class 
class fooBase(asd.fgh): 
    def qwerty(self): 
     print 'qwerty' 

# Now create a class that has methods and attributes of both classes 
class foo(FooBase, functions.foo): # Methods from FooBase take precedence 
    pass 

class foo(functions.foo, FooBase): # Methods from functions.foo take precedence  
    pass 

它利用了蟒蛇能力多重繼承創建新方法來自兩個來源的方法。

3

你想要execfile()。雖然你真的不這樣做,因爲重新定義了一堂課,呃......重新定義了它。

+0

+1爲「你真的不」,並始終知道做一些愚蠢的事情的好方法。我的第一個想法是使用`ast`模塊,然後使用`compile`和`exec`來實質上寫`execfile`:| – aaronasterling 2010-11-27 22:37:52

+1

@aronsterling:它不是*永遠*愚蠢的,介意你。我已經非常成功地將Django設置模塊拆分爲(非包)文件夾中的多個文件。 – 2010-11-27 22:41:18

+0

謝謝。我正在尋找合併類,但我也有這個功能的使用... – Blender 2010-11-27 23:17:48

0

python中的猴子修補不能以幾乎相同的方式工作。這通常被認爲是拙劣的形式,但如果你想反正這樣做,你可以這樣做:

# File 'functions.py' 

class foo(asd.fgh): 
    def __init__(self): 
    print 'foo' 

導入的模塊保持不變。在導入模塊中,我們做的事情完全不同。

# File 'main.py' 

import functions 

def qwerty(self): 
    print 'qwerty' 

functions.foo.qwerty = qwerty 

請注意,沒有額外的類定義,只是一個裸函數。然後我們將該函數添加爲該類的一個屬性。