2014-01-28 28 views
1

我想實現一個類的方法 - 該方法將使用類中的其他方法的結果,但它將是100多行的長度,所以我想定義方法在另一個文件中,如果可能。我怎樣才能做到這一點?事情是這樣的:爲其他地方的類定義方法

ParentModule.py

import function_defined_in_another_file 

def method(self): 
    return function_defined_in_another_file.function() 

ParentModule是我不想在定義函數的主要模塊

function_defined_in_another_file.py

import ParentModule 

def function(): 
    a = ParentModule.some_method() 
    b = ParentModule.some_other_method() 
     return a + b 

的功能在另一個文件中定義必須能夠使用ParentModule中可用的方法。

我是這麼做的嗎?或者有更好的辦法嗎?

+1

有一個單一的方法100行的長度是一個標誌是錯誤的 - 是否有部分它可以切割成更小的方法甚至獨立的功能?可以簡化的重複? – jonrsharpe

+0

你的問題的標題說「類的方法」,但你還沒有定義任何類。你真的在談論方法或獨立功能嗎? –

回答

3

你可以只分配方法的類:

import function_defined_in_another_file 

class SomeClass(): 
    method = function_defined_in_another_file.function 

它會被視爲就像任何其他的方法;您可以撥打methodSomeClass()的實例,其他SomeClass()方法可以用self.method()來調用它,而method()可以用self.method_name()調用任何SomeClass()方法。

您必須確保function()接受self參數。

+0

但是,我將不得不在ParentModule文件中定義函數?我想在另一個文件/模塊中定義它 – user1654183

+0

@ user1654183:對不起,您的模塊混合了 –

+0

謝謝!這更有意義。最後一件事: 「您必須確保函數()接受自我參數。」 在另一個文件中定義函數而不是類的一部分時,我該怎麼做? – user1654183