[ACCEPTED]-Python Class Inheritance issue-inheritance

Accepted answer
Score: 25

Three things:

  1. You need to explicitly call the constructor. It isn't called for you automatically like in C++
  2. Use a new-style class inherited from object
  3. With a new-style class, use the super() method available

This will look like:

class Person(object):
    AnotherName = 'Sue Ann'
    def __init__(self):
        super(Person, self).__init__()
        self.FirstName = 'Tom'
        self.LastName = 'Sneed'

    def get_name(self):
        return self.FirstName + ' ' + self.LastName

class Employee(Person):
    def __init__(self):
        super(Employee, self).__init__()
        self.empnum = 'abc123'

    def get_emp(self):
        print self.AnotherName
        return self.FirstName + ' ' + 'abc'

Using super 12 is recommended as it will also deal correctly 11 with calling constructors only once in multiple 10 inheritance cases (as long as each class 9 in the inheritance graph also uses super). It's 8 also one less place you need to change code 7 if/when you change what a class is inherited 6 from (for example, you factor out a base-class 5 and change the derivation and don't need 4 to worry about your classes calling the 3 wrong parent constructors). Also on the 2 MI front, you only need one super call to 1 correctly call all the base-class constructors.

Score: 9

You should explicitely call the superclass' init 1 function:

class Employee(Person):
    def __init__(self):
        self.empnum = "abc123"
Score: 5

Employee has to explicitly invoke the parent's 1 __init__ (not init):

 class Employee(Person):  
    def __init__(self):  
         self.empnum = 'abc123'  
Score: 2

Instead of super(class, instance) pattern why not just use super(instance) as 2 the class is always instance.__class__?

Are there specific 1 cases where it would not be instance.__class__?

More Related questions