1
我试图实现super()
每this SO回答。如何在python类中继承用户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标签。 –