类中的Python函数-名称错误:未定义函数
我刚刚开始在python中使用类,所以我想不出如何修复这个可能很简单的错误。我有一个类,基本上可以整理多个csv文件,对数据进行排序和清理,并输出完成的列表,如下所示:类中的Python函数-名称错误:未定义函数,python,python-3.x,class,nameerror,Python,Python 3.x,Class,Nameerror,我刚刚开始在python中使用类,所以我想不出如何修复这个可能很简单的错误。我有一个类,基本上可以整理多个csv文件,对数据进行排序和清理,并输出完成的列表,如下所示: class CollateCSV(): def __init__(self, input_dir="", file_list="", output=False): # initialises some global variables def read_file_list(self):
class CollateCSV():
def __init__(self, input_dir="", file_list="", output=False):
# initialises some global variables
def read_file_list(self):
#reads a csv file of already "dealt with" files
return x #list of filenames
def list_files_to_read(self, show=False, perm=True):
#gives list of csv files yet to be cleaned - the ones the program will actually import and read
return files_to_read
def sort_list(self, unsorted_list):
#sorts a list of OrderedDict by multiple keys
return sorted_list
def import_sort(self):
#reads each CSV file, cleans it, passes it to sort_list function and returns cleaned & sorted list of OrderedDict
return sort_list(x)
def return_final_list(self):
#does some things relating to logging if self.output == True. But used mainly as single easy place to return the final sorted & cleaned list of OrderedDict
return import_sort()
按照我设置项目的方式,这段代码与我的主代码在一个单独的文件中,因此我将其作为一个模块导入。因此,我知道代码本身的工作原理与运行下面的代码时一样,我在上面的代码中修复了一些错误,这些错误指示缺少变量或语法错误等
from convert import CollateCSV
x = CollateCSV("./csv_files", "./file_list.csv", output=False)
print(x.list_files_to_reas())
我遇到的问题是,当我运行上述代码时,我知道我得到了一个eror语句:
for file in list_files_to_read(show=False, perm=True):
NameError: name 'list_files_to_read' is not defined
我尝试在CollateCSV类中移动函数,并尝试在与第一个相同的文件中执行第二段代码,但仍然得到相同的错误。有人能给我一些关于python类的错误的建议吗?谢谢 在包含类文件的目录中,您可能缺少
\uuuu init\uuuu.py
文件
在for循环中,您需要编写
for file in x.list_files_to_read(show=False, perm=True):
# ...
由于
x
是从另一个方法调用方法的CollatesCSV
的实例,因此需要使用self
。我需要将.self添加到类中的所有函数吗?@user2757598您需要添加self
访问任何属性为什么当函数在类中时,您需要添加self。在调用它们之前,需要特定的名称空间做什么?@user2757598这是Python作用域/名称空间的工作方式。很简单,这些函数都在类名称空间中。要访问它们,必须访问类命名空间。您可以直接通过类,FooClass.method(foo\u instance,arg1,arg2)
(不执行此操作)或从实例:foo\u instance.method(arg1,arg2)
(执行此操作)。方法只是类名称空间中的一个函数,函数不知道这一事实。这就是为什么它需要self
(实例)作为参数的原因。这是用一些语言隐式完成的,例如Java,但不是Python.OK。可能您只是缺少了x
,如列表文件中的文件的to\u read(show=False,perm=True):