2017-04-17 75 views
0

我有一個類,我傳的文件清單,並在一個方法,它創建這些文件的列表:錯誤類功能 - 恰恰1參數

class Copy(object): 
    def __init__(self, files_to_copy): 
     self.files_to_copy = files_to_copy 

在這裏,它會創建一個文件列表:

def create_list_of_files(self): 
    mylist = [] 
    with open(self.files_to_copy) as stream: 
     for line in stream: 
      mylist.append(line.strip()) 
    return mylist 

現在,我嘗試訪問該方法的另一種方法在類:

def copy_files(self): 
    t = create_list_of_files() 
    for i in t: 
     print i 

然後我跑ŧ他以下if __name__ == "__main__"下:

a = Copy() 
a.copy_files() 

此拋出:

TypeError: create_list_of_files() takes exactly 1 argument (0 given) 

現在用的方法錯了嗎?

+1

'self.create_list_of_files()'< - 'self'是隱含的第一個參數。 –

+0

你得到這個錯誤表明你沒有正確縮進你的代碼(如果你不使用self,你將不能引用'create_list_of_files')。確保'create_list_of_files'縮進到與'__init__'相同的水平。 – Dunes

+2

[類中的Python調用函數]的可能重複(http://stackoverflow.com/questions/5615648/python-call-function-within-class) –

回答

1

你需要調用方法關閉self,這是「1個參數」的方法是尋找

t = self.create_list_of_files() 
0

你需要調用create_list_of_files如下: self.create_list_of_files()

0

你不及格任何變量的類。在你的init方法中,你的代碼指出init需要一個變量files_to_copy。您需要傳遞存儲正確信息的變量。例如:

class Copy(object): 
    def __init__(self, files_to_copy): 
     self.files_to_copy = files_to_copy 

#need to pass something like this: 
a = Copy(the_specific_variable) 
#now, can access the methods in the class 
相關問題