Python {NameError} name 'self' 在 __init__ 中未定义



我正在制作一个小型python脚本/程序,用于基于过滤关键字从某个医学院提取考试问题。

它一直工作得很好。我一直在添加越来越多的特性,改进兼容性,并做了一些调试。然而,突然现在脚本一直返回零问题,当进入调试模式时,我发现在__init__类函数的一行中出现了一个非常奇怪的NameError,以前一直工作得很好。我不太确定是什么触发了它,尽管IIRC我在那部分代码中做了一些小的调整。

在调试器中观察变量self.rawQuestions时,它似乎工作得很好,直到某一行代码出现NameError

同样值得注意的是,当涉及到编程时,我是一个初学者,所以如果这是一个非常愚蠢的错误,并且有一个明显的解决方案,我不会感到惊讶,对不起,如果是这样的话。但是当我搜索谷歌/stackoverflow类似的错误时,几乎所有的问题都使用了__init__类之外的self关键字,这是不同的。

这是一个小的节选与不相关的代码剪掉,错误发生在self.rawQuestions = [x for x...:

class Exam:
class Course:
...
class Question:
...
def __init__(self, text, path):
# Add text to text string
self.text = text
# Split text into questions
if re.search(r"(Q|q)uestion", self.text):
self.rawQuestions = self.text.rsplit("Question")
elif re.search(r"(F|f)råga", self.text):
self.rawQuestions = re.split(r"(?:F|f)råga(?=s)", self.text)

### ERROR IS ON LINE BELOW ###
# Filter out any questions containing only "Orzone..."
self.rawQuestions = [x for x in self.rawQuestions if not re.search(r"^(?<!w)s*d*s*Orzones*ABs*Gothenburgs*www.orzone.com.*$", x, flags=re.IGNORECASE|re.DOTALL)]
# Filter out questions containing a question, but with an "Orzone.. or Course at the end"
self.rawQuestions = [re.sub(r"sOrzones*ABs*Gothenburgs*www.orzone.com.*$", "", x) for x in self.rawQuestions]
# Delete course name and semester from questions then filter out empty questions
self.rawQuestions = [re.sub(rf"s*[w ]*{self.course.searchterm}.*[vh]t-?dd.*$", "", x) for x in self.rawQuestions]
self.rawQuestions = [x for x in self.rawQuestions if len(x) < 1]
# Make a list of question objects using the questions extracted using split
self.questions = []
for question in self.rawQuestions:
self.questions.append(self.Question(question, self))

这里的问题应该是你的'__ init __'方法上的缩进。试着这样修改:

class Exam:
def __init__(self, text, path):
# Add text to text string
self.text = text
# Split text into questions
if re.search(r"(Q|q)uestion", self.text):
self.rawQuestions = self.text.rsplit("Question")
elif re.search(r"(F|f)råga", self.text):
self.rawQuestions = re.split(r"(?:F|f)råga(?=s)", self.text)
# Filter out any questions containing only "Orzone..."
self.rawQuestions = [x for x in self.rawQuestions if not re.search(r"^(?<!w)s*d*s*Orzones*ABs*Gothenburgs*www.orzone.com.*$", x, flags=re.IGNORECASE|re.DOTALL)]
# Filter out questions containing a question, but with an "Orzone.. or Course at the end"
self.rawQuestions = [re.sub(r"sOrzones*ABs*Gothenburgs*www.orzone.com.*$", "", x) for x in self.rawQuestions]
# Delete course name and semester from questions then filter out empty questions
self.rawQuestions = [re.sub(rf"s*[w ]*{self.course.searchterm}.*[vh]t-?dd.*$", "", x) for x in self.rawQuestions]
self.rawQuestions = [x for x in self.rawQuestions if len(x) < 1]
# Make a list of question objects using the questions extracted using split
self.questions = []
for question in self.rawQuestions:
self.questions.append(self.Question(question, self))
class Course:
...
class Question:
...

最新更新