1

I'm trying to implement super() per this SO answer.

I have the following class:

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)

and the following subclass:

class User(Collection):
    def __init__(self, db, collection_name):
        super(User, self).__init__(db, collection_name)

Calling the Collection class works fine:

agents = Collection('hkpr_restore','agents')

Calling the subclass:

user = User('hkpr_restore','agents')

I get an error:

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

What am I doing wrong?

Community
  • 1
  • 1
DBWeinstein
  • 8,605
  • 31
  • 73
  • 118
  • You may want to do `Collection.client = ...` instead of `self.__class__.client = ...`, so that every subclass shares the same client and you use fewer connections. You may also use a global name instead of a class attribute. – Andrea Corbellini May 04 '15 at 12:01
  • If you're using Python 2 you should add a Python 2 tag to your question. – PM 2Ring May 04 '15 at 12:02

1 Answers1

1

Inherit Collection from object like Collection(object) to create a new style class. This way, super will work (it only works with new style classes).

Tasos Vogiatzoglou
  • 2,393
  • 12
  • 16
  • FWIW, all classes in Python 3 are new-style, so explicitly inheriting from `object` isn't need in Python 3. OTOH, writing `object` in Python 3 it doesn't hurt, and I guess it's nice to write code that performs properly on both Py 2 & Py 3, where practical. – PM 2Ring May 04 '15 at 12:04