2015-05-04 46 views
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 

我在做什麼錯?

+0

您可能希望執行'Collection.client = ...'而不是'self .__ class __。client = ...',以便每個子類共享同一個客戶端,並且使用更少的連接。您也可以使用全局名稱而不是類屬性。 –

+0

如果你使用的是Python 2,你應該爲你的問題添加一個Python 2標籤。 –

回答

1

繼承對象Collection(object)以創建新的樣式類。這樣,超級會工作(它只適用於新的風格類)。

+0

FWIW,Python 3中的所有類都是新的類型,所以在Python 3中不需要顯式繼承'object'。OTOH在Python 3中編寫'object'並不會造成傷害,我想這很好寫代碼可以在Py 2和Py 3上正確執行,並且可行。 –