无法从自定义python模块导入类

问题描述 投票:0回答:1

有一个空白的NatMailer/__init__.py

这是:NatMailer/NatMailer.py

# python -m smtpd -n -c DebuggingServer localhost:1025
class NatMailer:
    def __init__(self, smtp_server="localhost", port=1025, sender_email="[email protected]", debug=0):
        import logging

        logging.basicConfig(filename='example.log', level=logging.DEBUG)
        logging.info("Initiating NatMailer")

        import smtplib, ssl
        import json
        import csv
        import sqlite3

        sql = sqlite3.connect('example.db')
        self.debug = debug
        if (debug):
            self.smtp_server = "localhost"
            self.port = 1025
            self.sender_email = "[email protected]"
        else:
            self.smtp_server = smtp_server
            self.port = port
            self.sender_email = sender_email
    def send_email(self, receiver_email, message_contents):
        # Create a secure SSL context
        context = ssl.create_default_context()
        logging.info("Sending new email")

        # Try to log in to server and send email
        try:
            server = smtplib.SMTP(self.smtp_server,self.port)
            server.ehlo() # Can be omitted
            if (not self.debug):
                logging.info("Logging into " + self.sender_email)
                server.starttls(context=context) # Secure the connection
                server.ehlo() # Can be omitted
                server.login(self.sender_email, self.password)
            logging.info("Sending email to " + receiver_email)
            server.sendmail(self.sender_email, receiver_email, message_contents)
        except Exception as e:
            # Print any error messages to stdout
            logging.debug(e)
        finally:
            server.quit()

然后在debug_driver.py外面有一个NatMailer/

import NatMailer
debug = 1
nm = NatMailer.NatMailer(debug=debug)
message = """\
            Subject: Hi there

            This message is sent from Python."""
nm.send_email('[email protected]', message)

我收到此错误:

Traceback (most recent call last):
  File "C:/Users/pat/PycharmProjects/NatMailer/debug_driver.py", line 3, in <module>
    nm = NatMailer.NatMailer(debug=debug)
AttributeError: module 'NatMailer' has no attribute 'NatMailer'

Process finished with exit code 1

我究竟做错了什么?我希望能够将自定义类导入到我的debug_driver.py脚本中。

python
1个回答
2
投票

这里涉及三个级别:目录(包),文件名(模块)和类。 NatMailer指的是包,NatMailer.NatMailer指的是模块,NatMailer.NatMailer.NatMailer指的是类。

所以你需要类似的东西

# import module from package
import NatMailer.NatMailer  

debug = 1
nm = NatMailer.NatMailer.NatMailer(debug=debug)

错误消息的简要说明:

AttributeError: module 'NatMailer' has no attribute 'NatMailer'

您只导入包(或模块,如此处所述):

import NatMailer

这基本上只加载__init__.py文件,它是空的。因此,当您尝试访问该模块的任何内容时,Python会抱怨,因为那里什么都没有:

NatMailer.NatMailer

该属性不存在:它不是(子)模块,因为它不是在__init__.py中导入的,也不是类,因为它也没有在__init__.py中导入。它基本上是一个近乎空的导入,你必须明确导入NatMailer.NatMailer。但请参见上下文。


备择方案:

1/

# import module from package
from NatMailer import NatMailer  

debug = 1
nm = NatMailer.NatMailer(debug=debug)

2/

# import class from the module directly
from NatMailer.NatMailer import NatMailer  

debug = 1
nm = NatMailer(debug=debug)

3 /或许更多涉及,但经常使用:

把它放在你的包__init__.py中:

from .NatMailer import NatMailer

然后使用

# import the class from package
# note: now you can't distinguish the class from the module.
# see the remark at the bottom about naming conventions
from NatMailer import NatMailer  

debug = 1
nm = NatMailer(debug=debug)

由于NatMailer类现在可以在包级别找到,而不仅仅是在模块级别。


注意:包和模块通常不是CamelCased。这会让事情变得更有洞察力:natmailer.natmailer.NatMailer将是你的班级。

© www.soinside.com 2019 - 2024. All rights reserved.