使用super()调用重载方法会产生AttributeError

时间:2016-06-15 10:22:20

标签: python oop

我有类定义,如

from tinydb import TinyDB

class DB(TinyDB):
    def __init__(self, filename):
        return super(DB, self).__init__(filename)

    def exists(self, url):
        return bool(self.search(Entry.url == url))

    def insert(self, *args, **kwargs):
        if len(self) > 100:
            self.purge_tables()

        return super(DB, self).insert(*args, **kwargs)

其中TinyDB is from the tinydb package

我现在尝试运行

database = db.DB('test.json')
database.insert({'title': 'Hello', 'url': 'foo'})

我收到错误消息

return super(DB, self).insert(*args, **kwargs)
AttributeError: 'super' object has no attribute 'insert'

而我在做的时候

from tinydb import TinyDB

database2 = TinyDB('test.json')
database2.insert({'title': 'Hello', 'url': 'foo'})

insert()在那里,provided by

def __getattr__(self, name):
    """
    Forward all unknown attribute calls to the underlying standard table.
    """
    return getattr(self._table, name)

似乎有一些错综复杂的方法可以让你的班级中的一个属性的属性可以被外部访问。

1 个答案:

答案 0 :(得分:1)

您的上一个示例有效,因为__getattr__上定义了TinyDB方法:

class TinyDB(object):
    # [....]
    def __getattr__(self, name):
        """
        Forward all unknown attribute calls to the underlying standard table.
        """
        return getattr(self._table, name)

事实上,insert方法是在Table上定义的。您可以使用以下方法修复您的示例:

def insert(self, *args, **kwargs):
    if len(self) > 100:
        self.purge_tables()

    return self._table.insert(*args, **kwargs)

this answer有更多解释为什么它不能像你期望的那样工作。