欢迎访问宙启技术站
智能推送

Python中的构造函数__init__()和继承中的调用顺序分析

发布时间:2023-12-27 15:19:24

在Python中,每个类都可以有一个特殊的方法叫做构造函数(__init__()),它会在创建对象时被调用。构造函数用于初始化对象的属性和执行一些必要的初始化操作。当一个对象被创建时,Python会自动调用该类的构造函数来完成这些任务。构造函数的用法如下:

class MyClass:
    def __init__(self, arg1, arg2):
        self.arg1 = arg1
        self.arg2 = arg2
        
    def some_method(self):
        # do something

在继承中,如果一个子类没有定义自己的构造函数,那么它会默认调用父类的构造函数来初始化继承的属性。在子类中调用父类的构造函数有两种方式:

1. 使用super()函数来调用父类的构造函数:

class ChildClass(ParentClass):
    def __init__(self, arg1, arg2, arg3):
        super().__init__(arg1, arg2)
        self.arg3 = arg3

2. 调用父类的构造函数方法:

class ChildClass(ParentClass):
    def __init__(self, arg1, arg2, arg3):
        ParentClass.__init__(self, arg1, arg2)
        self.arg3 = arg3

下面通过一个例子来说明构造函数和继承中调用顺序的相关问题:

class ParentClass:
    def __init__(self):
        self.parent_attribute = "Parent attribute"
        print("Parent constructor")

    def parent_method(self):
        print("Parent method")


class ChildClass(ParentClass):
    def __init__(self):
        super().__init__()
        self.child_attribute = "Child attribute"
        print("Child constructor")

    def child_method(self):
        print("Child method")

        
child = ChildClass()

输出结果:

Parent constructor
Child constructor

在上面的例子中,我们定义了一个父类ParentClass和一个子类ChildClass。子类继承了父类的构造函数,并可以在自己的构造函数中进行初始化操作。在创建子类的对象时,会先调用父类的构造函数,然后再调用子类的构造函数。因此,输出结果中先出现了"Parent constructor",然后是"Child constructor"。

需要注意的是,如果子类没有定义自己的构造函数,而父类有定义构造函数,那么子类会直接调用父类的构造函数并执行其操作。