【发布时间】:2021-10-23 17:55:06
【问题描述】:
我正在制作一个小型 python 脚本/程序,用于根据过滤关键字从某个医学院提取考试问题。
它运行良好。我一直在添加越来越多的功能并提高兼容性,并进行了一些调试。但是,突然之间,脚本一直返回零问题,进入调试模式时,我发现类__init__函数中的一行出现了一个非常奇怪的NameError,它一直运行良好前。我不太确定是什么触发了它,尽管 IIRC 我在代码的那部分做了一些小的调整。
在调试器中查看有问题的变量self.rawQuestions 时,它似乎工作正常,直到某一行代码出现NameError。
另外值得注意的是,在编程方面我是初学者,所以如果这是一个非常愚蠢的错误并有一个明显的解决方案,我不会感到惊讶,如果是这样的话,我很抱歉。但是当我在 google/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*Orzone\s*AB\s*Gothenburg\s*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"\sOrzone\s*AB\s*Gothenburg\s*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-?\d\d.*$", "", 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与class不同。 Python 区分大小写。代码应引发错误,指出Class未定义。你有一个错字。你写的是Class而不是class -
哎呀,这也只是在 SO 上不正确,而不是在我的代码中......对不起。它在我的代码中显示类。
标签: python variables self re self-reference