简体   繁体   中英

Run Overriden Method Automatically From Base Class

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'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM