错误类功能 - 恰恰1参数
问题描述:
我有一个类,我传的文件清单,并在一个方法,它创建这些文件的列表:错误类功能 - 恰恰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)
现在用的方法错了吗?
答
你需要调用方法关闭self
,这是“1个参数”的方法是寻找
t = self.create_list_of_files()
答
你需要调用create_list_of_files
如下: self.create_list_of_files()
答
你不及格任何变量的类。在你的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
'self.create_list_of_files()'
你得到这个错误表明你没有正确缩进你的代码(如果你不使用self,你将不能引用'create_list_of_files')。确保'create_list_of_files'缩进到与'__init__'相同的水平。 – Dunes
[类中的Python调用函数]的可能重复(http://stackoverflow.com/questions/5615648/python-call-function-within-class) –