在Python中调用超类的类方法

我正在开发Flask扩展,为Flask添加了CouchDB支持.为了更容易,我已经将couchdb.mapping.Document子类化,因此存储和加载方法可以使用当前的线程本地数据库.现在,我的代码看起来像这样:

class Document(mapping.Document):
  # rest of the methods omitted for brevity
  @classmethod
  def load(cls, id, db=None):
    return mapping.Document.load(cls, db or g.couch, id)

为简洁起见,我遗漏了一些,但那是重要的部分.但是,由于classmethod的工作方式,当我尝试调用此方法时,我收到错误消息

  File "flaskext/couchdb.py", line 187, in load
    return mapping.Document.load(cls, db or g.couch, id)
TypeError: load() takes exactly 3 arguments (4 given)

我测试了用mapping.Document.load.im_func(cls,db或g.couch,id)替换调用,它可以工作,但我对访问内部im_属性并不是特别高兴(即使它们已被记录).有没有人有更优雅的方式来处理这个?

最佳答案 我想你实际上需要在这里使用super.无论如何,这是调用超类方法的更简洁的方法:

class A(object):
    @classmethod
    def load(cls):
        return cls

class B(A):
    @classmethod
    def load(cls):
        # return A.load() would simply do "A.load()" and thus return a A
        return super(B, cls).load() # super figures out how to do it right ;-)


print B.load()
点赞