python - 如何防止 python 中的名称错误错误?

标签 python

当我运行我的程序 core.py ( http://pastebin.com/kbzbBUYd ) 时,它返回:

文件“core.py”,第 47 行,文本格式 core.mail(numbersendlist, messagetext) NameError: 全局名称 'core' 未定义

谁能告诉我这是怎么回事,我该如何阻止这个错误?

如果有帮助,core.py 中的“import carrier”行指的是 carrier.py ( http://pastebin.com/zP2RHbnr )

最佳答案

您收到 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.')

关于python - 如何防止 python 中的名称错误错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2351904/

相关文章:

Python:打开具有定义的驱动器盘符的文件 - TypeError:需要整数

python - 如何增加刻度线之间的间距(或减少刻度线数量)

python - 这是什么? (行继续字符后出现意外字符)

python - 如何与合作伙伴分享我正在开发的网站?

python - 单步执行时应用GDB FrameDecorator

python - 将字典值映射到列表

python - Numba 并行代码比顺序代码慢

Python,通过提取字符和数字子串来解析字符串

python - 如何使用十六进制 Ascii 中特定位数的字符串格式

python - 如何在 Google Colaboratory 中显示行号?