2015-05-04 48 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上正确执行,并且可行。 –