【发布时间】:2015-05-04 11:51:08
【问题描述】:
我正在尝试按照this SO 答案实施super()。
我有以下课程:
class Collection():
"""returns a collection curser from mongodb"""
def __init__(self, db, collection_name):
self.db = db
self.collection_name = collection_name
if not hasattr(self.__class__, 'client'):
self.__class__.client = MongoClient()
self.data_base = getattr(self.client, self.db)
self.collection = getattr(self.data_base, self.collection_name)
以及以下子类:
class User(Collection):
def __init__(self, db, collection_name):
super(User, self).__init__(db, collection_name)
调用Collection 类可以正常工作:
agents = Collection('hkpr_restore','agents')
调用子类:
user = User('hkpr_restore','agents')
我收到一个错误:
Traceback (most recent call last):
File "main.py", line 37, in <module>
user = User('hkpr_restore','agents')
File "filepath/user.py", line 35, in __init__
super(User, self).__init__(db, collection_name)
TypeError: must be type, not classobj
我做错了什么?
【问题讨论】:
-
您可能想要使用
Collection.client = ...而不是self.__class__.client = ...,这样每个子类共享同一个客户端,并且您使用的连接更少。您也可以使用全局名称而不是类属性。 -
如果你使用的是 Python 2,你应该在你的问题中添加一个 Python 2 标签。
标签: python inheritance super