【问题标题】:Python function definition not workingPython函数定义不起作用
【发布时间】:2013-07-07 00:27:43
【问题描述】:

我遇到了一个在 Python 类中定义的函数的问题:

class DatabaseHandler:

    def get_messages_by_last_mid(self, uidReceiver, last_mid):

        self.cursor.execute("SELECT uidSender, content FROM messages WHERE MID > ?", str(last_mid))

        ret_value = []
        result = self.cursor.fetchone()
        while result != None:
            ret_value.append(result)
            result = self.cursor.fetchone()

        return ret_value

    def get_messages_by_last_group_id(self, uidReceiver, last_gid):

        self.cursor.execute("SELECT gidreceiver, uidsender, content FROM groupmessages WHERE mid > ?", str(last_gid))

        ret_value = []
        result = self.cursor.fetchone()
        while result != None:
           ret_value.append(result)
           result = self.cursor.fetchone()

        return ret_value

但只有函数 get_messages_by_last_mid() 有效,另一个产生以下错误:

AttributeError: DatabaseHandler instance has no attribute 'get_messages_by_last_group_id'

提前致谢:)

【问题讨论】:

  • 您的缩进错误。这是您的代码在实际源文件中缩进的方式吗?如果是这样,那将导致问题。
  • 您的类的构造函数似乎丢失了。如果get_messages_by_last_mid() 有效,那么self 会从某个地方获得cursor 属性。这是你的整个DatabaseHandler 班级吗?
  • 缩进现在与源文件中的一样。它还包含一个构造函数:def __init__(self, database): self.db = sqlite3.connect(database) self.db.text_factory = str

标签: python function definition


【解决方案1】:

如果您来自其他各种编程语言,缩进可能是 Python 中的无声杀手。如您所知,缩进是 Python 在您编写代码时确定方法、函数、类、循环等范围的方式。确保你的缩进是一致的!你可以使用命令行选项 -t 或 -tt to python 来检查自己。

【讨论】:

  • DatabaseHandler 类作为 Python 模块安装。正如我已经回答的那样,python -t DatabaseHandler.py 不返回任何内容
【解决方案2】:

对不起,我用的是旧包。 我的问题已经解决了。 感谢您的回答。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多