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

2024-04-20 11:47:25 发布

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

我有一个类定义,比如

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)

其中^{} is from the ^{} 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)

通过这种方式使类中的一个属性的属性可以被外部访问,这似乎有些复杂。你知道吗


Tags: fromimportselfurldbreturninitdef
1条回答
网友
1楼 · 发布于 2024-04-20 11:47:25

上一个示例之所以有效,是因为在TinyDB上定义了__getattr__方法:

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对为什么它不能像您期望的那样工作有更多的解释。你知道吗

相关问题 更多 >