首页 > 解决方案 > 为什么当我们使用类名调用超类的构造函数时我们传递 self 而使用 super 时却没有

问题描述

正如您可以看到下面提供的代码,我在 python 中使用 OOP 并发现了一些我无法理解的东西。据我所知,我们可以通过使用 super() 或类名本身来调用超类的构造函数,但是如果我在 #001 行中传递 self ,则在 #001 和 #002 行中,它会给我一个错误,如果我这样做不要在 #002 中传递 self 它再次给我一个错误。那么为什么通过这两种方法调用超类的构造函数时传递和不传递self有区别呢?如果有区别,为什么在使用类名的情况下我们还要传递 self ,因为 self 指的是子类的对象,不是吗?

class A:
    def __init__(self,a):
        self.a = a
        print('Printing self from constructor of A:')
        print(self)
        print('Printing self from constructor of B ends.\n')
    def get_a(self):
        print('-----------A-------------')
        print(self,'\n',self.get_a)
        print('-----------A-------------\n')
class B(A): 
    def __init__(self,a,b):
        #001 super().__init__(a)
        #002 A.__init__(self,a)
        print('Printing self from constructor of B:')
        print(self)
        print('Printing self from constructor of B ends.\n')
        self.b = b
    def get_b(self):
        #self.get_a works but get_a() doesn't
        print('-----------B-------------') 
        print(self,'\n',self.get_a,'\n')
        print(self,'\n',self.get_b)
        print('-----------B-------------\n')

a = A(5)
b = B(50,60)
a.get_a()
b.get_a()
b.get_b()

标签: pythonclassoopobjectinheritance

解决方案


推荐阅读