[ACCEPTED]-Python Class Inheritance issue-inheritance
- You need to explicitly call the constructor. It isn't called for you automatically like in C++
- Use a new-style class inherited from object
- 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.
You should explicitely call the superclass' init 1 function:
class Employee(Person): def __init__(self): Person.__init__(self) self.empnum = "abc123"
Employee has to explicitly invoke the parent's 1 __init__ (not init):
class Employee(Person): def __init__(self): Person.__init__(self) self.empnum = 'abc123'
super(class, instance) pattern why not just use
super(instance) as 2 the class is always
Are there specific 1 cases where it would not be
More Related questions