Python 类中的函数出错-仅接受1个参数
我有一个类,我在其中传递一个文档列表,在一个方法中,它创建了一个文档列表:Python 类中的函数出错-仅接受1个参数,python,class,methods,Python,Class,Methods,我有一个类,我在其中传递一个文档列表,在一个方法中,它创建了一个文档列表: 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:
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\uuuuu name\uuuuu==\uuuuuuu main\uuuuu下运行以下命令:
这引发了:
TypeError: create_list_of_files() takes exactly 1 argument (0 given)
我使用的方法是否错误?您需要按如下方式调用创建\u列表\u文件:
self.create_list_of_files您需要将该方法调离self,这是该方法要查找的1个参数
t = self.create_list_of_files()
您没有向类传递任何变量。在init方法中,代码声明init接受一个变量files\u to\u 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。确保\u文件的创建\u列表\u缩进到与\u初始化\u相同的级别。可能重复
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