在 Python 中调用超类的类方法 [英] Invoking a superclass's class methods in Python
问题描述
我正在为 Flask 添加 CouchDB 支持的 Flask 扩展.为方便起见,我对 couchdb.mapping.Document
进行了子类化,以便 store
和 load
方法可以使用当前线程本地数据库.现在,我的代码如下所示:
I am working on a Flask extension that adds CouchDB support to Flask. To make it easier, I have subclassed couchdb.mapping.Document
so the store
and load
methods can use the current thread-local database. Right now, my code looks like this:
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 的工作方式,当我尝试调用此方法时,收到错误消息
I left out some for brevity, but that's the important part. However, due to the way classmethod works, when I try to call this method, I receive the error message
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 or g.couch, id)
替换调用,它有效,但我对访问内部不是特别满意im_
属性(即使它们被记录在案).有没有人有更优雅的方法来处理这个问题?
I tested replacing the call with mapping.Document.load.im_func(cls, db or g.couch, id)
, and it works, but I'm not particularly happy about accessing the internal im_
attributes (even though they are documented). Does anyone have a more elegant way to handle this?
推荐答案
我认为您实际上需要在这里使用 super
.无论如何,这是调用超类方法的更简洁的方法:
I think you actually need to use super
here. That's the neater way to call superclass methods anyway:
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()
这篇关于在 Python 中调用超类的类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!