Pythons的AttributeError:“NoneType”对象没有属性“errors”

2024-03-29 12:00:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道它已经在这里很多次了,但我没有找到我的案件的正确答案。
首先:我正在制作一个简单的数据库系统(对我自己来说),它将不使用散列等(至少现在是这样)。现在我被卡住了。

import sys
import os

filename = ""
database = ""
path = ""
table = ""

class Nollty:
    returns = 0
    errors = 0

    def __init__(self, filename, database):
        self.filename = filename
        self.database = database
        self.path = self.filename + "databases/" + self.database
        openfile = open(self.path + "/db_required", "r")
        if not openfile.errors:
            self.returns = 1
        if not os.path.exists(self.path + "/db_required"):
            self.returns = 0
        openfile.close();

    def select(self, table):
        errors = 0
        self.table = table
        openfile = open(self.path + "/" + self.table, "r")
        if not openfile.errors:
            errors = 1
        if not os.path.exists(self.path + "/" + self.table):
            errors = 0
        openfile.close();


nollty = Nollty("", "test")
if nollty.returns == 1:
    print "Successfully connected to the database!"

query = nollty.select("aaa_auto")
if query.errors == 0:
    print "Successfully chosen the table!"

错误输出为:

Traceback (most recent call last):
File "/home/spotrudloff/Python/Nollty/nollty.py", line 40, in <module>
if query.errors == 0:
AttributeError: 'NoneType' object has no attribute 'errors'

问题可能是我是一个PHP程序员,我今天只花了几个小时就学会了Python(所以我的想法还是“PHPy”)。

谢谢你的回复。


Tags: pathimportselfifostablenotfilename
3条回答

select()不返回显式值,因此它有一个NoneType返回值。更改代码,使select()返回1或0,具体取决于代码的成功或失败。

使用returnserrors作为类变量似乎不是一个好主意。每个变量只有一个实例,不管您创建了多少个Nollty实例。相反,请执行以下操作:

def __init__(self, filename, database):
    self.returns = 0
    self.errors = 0
    # rest of __init__

接下来,使用returns来表示返回值似乎也不是一个好主意。在Python中,通常会引发异常来指示构造函数中的问题。这样,调用者就不能因为忘记检查returns而简单地忽略问题。

类似地,使用select()中的异常来指示参数有问题。我的建议是同时消除returnserrors

您也不会从select返回任何值,所以query最终成为None(在Python中,None是一个特殊值)。您要么希望从select()返回有用的内容,要么不将其结果赋给任何不返回有用值的内容。

看起来select()没有返回值,所以它默认为NoneType(null)。或者(您可能打算这么做),将query更改为nollty。

相关问题 更多 >