简体   繁体   English

从基类自动运行重写方法

[英]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. 在下面,我实现了print_info以自动从基类Person运行,但是当我初始化子类时,我收到一个错误,因为看来print_info仅从基类而非子类运行。

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. 问题在于,在您调用print_info() self.employee_code尚未定义,因为在分配超类之前会调用它的构造函数。 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. 请注意,仅当您在构造函数中使用重写方法(取决于子类数据)时,才会出现问题,通常可以使用超类代码中的重写方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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