Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Is this the preferred/confect way to write class inheritance with parameters?

class Collection():
    def __init__(self, db):
        self.x = db

    def printDbName(self):
        print self.x

parent = Collection('hkpr')

parent.printDbName()

class Document(Collection):
    def __init__(self, db):
        self.db = db
        Collection.__init__(self, self.db)

    def printChild(self):
        print self.x

child = Document('yabba')
child.printChild()
child.printDbName()
share|improve this question

closed as off-topic by jonrsharpe, JS1, 200_success May 5 at 8:03

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer 1

I have a few small remarks:

Constructor

If you use Python 2.x, You might consider to use

super(Document,self).__init__(self.db)

instead of

Collection.__init__(self, self.db)

If you use python 3, you can even do it simpler by using:

super().__init__(self.db)

In addition, it's more a convention to first call the constructor on your parent and then perform the other tasks.

The benefit of this approach? read here to be convinced.


Base class

You might consider to inherit your Collection class from the object class.

class Collection(object):

this is a historical issue, which can end up in problems if you happen to use different python versions. It makes Collection a 'new style' object.

New style objects have a different object model to classic objects, and some things won't work properly with old style objects, for instance, super(), @property, etc..


Main function

Right now you defined your 'program' code between your classes. This is

  1. Not readable
  2. Hard to maintain

You might consider using a main function, like:

if __name__ == "__main__":
    main()

where the main() function in your case will look like:

parent = Collection('hkpr')
parent.printDbName()
child = Document('yabba')
child.printChild()
child.printDbName()

Good luck!

share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.