Reputation: 2472
In the case of inheritance, what is the best way to automatically run a method out of the base class that each child overrides. Below I implemented print_info to automatically run from the base class Person but when I initialize a child class I get an error since it appears that print_info is just being run from the base class only, not the child.
class Person:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
self.print_info()
def print_info(self):
print('{} {}'.format(self.fname, self.lname))
class Employee(Person):
def __init__(self, fname, lname, employee_code):
super().__init__(fname, lname)
self.employee_code = employee_code
def print_info(self):
print('{} {} has employee code {}'.format(self.fname, self.lname, self.employee_code))
e = Employee('Jon', 'Taylor', 'jtaylor')
error
AttributeError: 'Employee' object has no attribute 'employee_code'
Upvotes: 2
Views: 47
Reputation: 59701
The problem is that at the point at which you are calling print_info()
self.employee_code
has not yet been defined, because the constructor of the superclass is called before it is assigned. One possibility is to reorder the constructor of the child class:
class Employee(Person):
def __init__(self, fname, lname, employee_code):
self.employee_code = employee_code
super().__init__(fname, lname)
This is generally not recommended, as the best practice is to call the constructor of the superclass before anything else in the constructor of the subclass, but you can do it.
Note that the problem only appears when you use the overridden method (which depends on subclass data) in the constructor like that, using overridden methods from superclass code is generally ok.
Upvotes: 3