'NoneType' 没有属性(使用 pyodbc/sql 连接)

'NoneType' has not attribute (using pyodbc/sql connection)

想知道为什么 Python returns 'NoneType' object has no attribute 'connection' 使用下面的代码。我相信我已经在 class 中正确创建了 self.connection 变量,但试图使用实例 returns 调用它时出现上述错误。连接是否在我检索 connection 属性之前以某种方式终止?

import pyodbc

class sql:
    
    def __init__(self):
        
        self.driver = "{ODBC Driver 17 for SQL Server}"
        self.server = ".\SQLEXPRESS"
        self.database = "lotto"
        self.trusted_connection = "YES"
        self.mars_connection = "YES"

    def sql_conn(self):
        
        """Connect to local SQL Server"""
        
        print('\nConnecting to SQL Server...')
    
        self.connection = pyodbc.connect(
            'DRIVER=' + self.driver
            + ';SERVER=' + self.server
            + ';DATABASE=' + self.database
            + ';Trusted_Connection=' + self.trusted_connection
            + ';MARS_CONNECTION=' + self.mars_connection
        )

        print(self.connection)
        self.cursor = self.connection.cursor()
        
        print('\nConnection to SQL Server established.')

sql_instance = sql()
conn = sql_instance.sql_conn().connection

sql_conn() 没有明确地 return 任何东西,所以它隐含地 returns None.

在不更改方法的情况下解决此问题的一种方法是将最后一行分成两行 - 一行用于初始化连接,另一行用于检索连接:

sql_instance = sql()
sql_instance.sql_conn()
conn = sql_instance.connection