如何防止Python中的名称错误?
当我运行我的程序 core.py(http://pastebin.com/kbzbBUYd)时,它返回了以下错误信息:
文件 "core.py",第 47 行,在 texto 函数中 core.mail(numbersendlist, messagetext) NameError: global name 'core' is not defined
有人能告诉我发生了什么,以及我该如何解决这个错误吗?
如果有帮助的话,core.py 中的 "import carrier" 这一行是指向 carrier.py(http://pastebin.com/zP2RHbnr)的。
2 个回答
1
你还没有定义过 core
这个名字。我想你是想写类似下面的内容:
core = Core('username', 'password')
然后再调用 texto
吗?
6
你遇到的 NameError
错误是因为在你的代码中,没有定义名为 core
的东西,无论是在本地还是全局范围内。你需要先创建一个 Core
对象,然后才能调用它的方法。
另外,texto()
的缩进可能也有问题。这样的话,你就无法在模块的其他部分使用这个函数。如果你想在当前模块的其他地方或者其他模块中使用它,你需要在模块级别声明这个函数,或者使用 @staticmethod
装饰器来把它变成类的静态方法。
这样做应该就能正常工作了。
import smtplib
from email.MIMEMultipart import MIMEMultipart
from email.MIMEText import MIMEText
import carrier
class Core:
def __init__(self, username, password):
# code could be added here to auto load these from a file
self.gmail_user = username
self.gmail_pwd = password
# Send one text to one number
# TODO: send to multiple addresses
def mail(self, to, text):
msg = MIMEMultipart()
msg['From'] = self.gmail_user
msg['To'] = to
msg.attach(MIMEText(text))
mailServer = smtplib.SMTP("smtp.gmail.com", 587)
mailServer.ehlo()
mailServer.starttls()
mailServer.ehlo()
mailServer.login(self.gmail_user, self.gmail_pwd)
mailServer.sendmail(self.gmail_user, to, msg.as_string())
# Should be mailServer.quit(), but that crashes...
mailServer.close()
def texto(sendtoaddress, messagetext):
numbersendlist = []
for number in sendtoaddress:
numbersendlist.append(carrier.carriercheck(number))
core = Core('username', 'password')
for number in numbersendlist:
core.mail(number, messagetext)
texto(['1112223333'], 'hi. this better work.')