我有类定义,如
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)
似乎有一些错综复杂的方法可以让你的班级中的一个属性的属性可以被外部访问。
答案 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有更多解释为什么它不能像你期望的那样工作。