2016-11-09 50 views
0

我一直在論壇上尋找答案,而我發現的最相似的是:Python: How to call class method from imported module? 「Self」 argument issue。但它不能解決我的問題。Python 2.7 - 如何從導入的模塊調用類方法? 「自我」的說法

我有2個腳本:1-X和2-Y。我需要與Y進口一些高清()到X,這裏是我的代碼,我導入和實例:

X腳本 - 它,我有一個名爲txtCorpus變量,它是一個我打算操縱

import Y 
from Y import PreProcessing 
txtCorpus 
def status_processing(txtCorpus): 
    instance = PreProcessing() #Here is where to instantiate the class contained within the Y script and where it has some defs that I need 
    myCorpus = instance.initial_processing(txtCorpus) 
#After some other lines of operation ... 
if __name__ == "__main__": 
    status_processing(txtCorpus) 

現在腳本Ÿ

class PreProcessing(): 
    @property 
    def text(self): 
     return self.__text 

    @text.setter 
    def text(self, text): 
     self.__text = text 

tokens = None 
def initial_processing(self): 
#Operations 

當我執行它的存在的方式,顯示了以下錯誤:

TypeError: initial_processing() takes exactly 1 argument (2 given) 

當我這樣做myCorpus = instance.initial_processing(),顯示以下錯誤:

AttributeError: PreProcessing instance has no attribute '_PreProcessing__text' 

什麼是我必須實例的代碼時,我通過txtCorpus作爲參數的工作方式?

+0

'從Y import Y-class'那是無效的語法。請正確複製粘貼代碼。 –

+0

@AlexHall我很確定這不是複製和粘貼錯誤。 –

+0

'從Y進口Yclass'跟着行'txtCorpus'仍然是錯誤的。 –

回答

0

您不包括完整爲例,但你在這裏看到的TypeError: initial_processing() takes exactly 1 argument (2 given)錯誤是因爲你定義initial_processing這樣:

def initial_processing(self): 

其中僅需要1個參數(類的實例)。然後,你通過它有兩個參數(instancetxtCorpus):

myCorpus = instance.initial_processing(txtCorpus) 

思考的類方法是這樣的:

instance.initial_processing(txtCorpus) 
# equivalent to 
initial_processing(instance, txtCorpus) 

所以你通過2個參數,但只定義處理1的方法。因此,您需要將其定義爲需要兩個參數:

def initial_processing(self, txt): 
# code here 
+0

好的。我改變'高清initial_processing(個體經營):''到高清initial_processing(個體經營,文字):' 因此,我調用我收到此錯誤的方法'myCorpus = instance.initial_processing(txtCorpus)'和 :'返回self .__文本 AttributeError:預處理實例沒有屬性'_PreProcessing__text' ' –

0

看起來問題是您的函數不是您認爲它的類的一部分。你應該縮進它,使它成爲類的一部分,並添加一個參數讓它接受(txtCorpus)。

class PreProcessing(): 
    def __init__(self): 
     self.__text = None 

    @property 
    def text(self): 
     return self.__text 

    @text.setter 
    def text(self, text): 
     self.__text = text 

    tokens = None # Not sure what this is for...? 
    def initial_processing(self, txt): 
      #Operations 
+0

好的。我改變了'def initial_processing(self):'def'initial_processing(self,text):'所以我調用了myCorpus = instance.initial_processing(txtCorpus)''方法',並且我收到了這個錯誤:return self .__ text AttributeError:預處理實例沒有屬性「_PreProcessing__text'' –

+0

@ LeandroS.Matos這聽起來像你沒有創建實例變量'__text'。試着在你的構造函數中這樣做,就像通過添加我剛編輯我的答案的'__init__'方法一樣。 – user108471

0

的錯誤是,定義,當你需要把兩個參數,一個爲自己和一個用於txtCorput

def initial_processing(self, txt): 
    # Operations 

Ÿ文件:

class PreProcessing(): 
    @property 
    def text(self): 
     return self.__text 

    @text.setter 
    def text(self, text): 
     self.__text = text 

    tokens = None 
    def initial_processing(self, corpus): 
    # Operations 

有什麼錯你的X腳本(除了你正在導入Yclass不是預處理^^)