加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

在Python中调用超类的类方法

发布时间:2020-12-20 11:14:04 所属栏目:Python 来源:网络整理
导读:我正在开发Flask扩展,为Flask添加了CouchDB支持.为了更容易,我已经将couchdb.mapping.Document子类化,因此存储和加载方法可以使用当前的线程本地数据库.现在,我的代码看起来像这样: class Document(mapping.Document): # rest of the methods omitted for b
我正在开发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,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()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读