Reputation: 4807
I am trying to learn super implementation in Python and I have tried various help threads on SO but I am not able to implement the following code:
class Person:
def __init__(self, first, last, age):
self.firstname = first
self.lastname = last
self.age = age
def __str__(self):
return self.firstname + " " + self.lastname + ", " + str(self.age)
class Employee(Person):
def __init__(self, first, last, age, staffnum):
super(Employee, self).__init__(first, last, age)
self.staffnumber = staffnum
def __str__(self):
return super(Employee, self).__str__() + ", " + self.staffnumber
x = Person("Marge", "Simpson", 36)
y = Employee("Homer", "Simpson", 28, "1007")
print(x)
print(y)
What is wrong with this syntax in above code?
return super(Employee, self).__str__() + ", " + self.staffnumber
Upvotes: 0
Views: 15
Reputation: 25895
In Python 2.7 there are leftovers of the old hierarchy. Not all classes inherit from object
, which is the default in Python 3. If you do not explicitly inherit object
Python will use old style objects, which fail with Super
which depends on this.
All you need to do is explicitly make sure all your objects eventually inherit object
:
class Person(object):
In Python 3 this is 'fixed'.
An alternative is to forego super in favor of using the methods as class methods, which will work with both types of objects:
Person.__init__(self,first,last,age)
Person.__str__(self)
Upvotes: 1