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標籤。 –