为什么当我们使用类名调用超类的构造函数但不使用super时却传递self

时间:2019-04-26 11:06:49

标签: python class oop object inheritance

如您所见,下面提供的代码是,我正在python中使用OOP进行游戏,并且发现了我无法解决的问题。 据我所知,我们可以通过使用super()或类名本身来调用超类的构造函数,但如果在#001行和#002行传递self,则会在这里出现#001和#002行,这会给我一个错误,如果执行没有通过#002自我传递,这再次给我一个错误。 那么,为什么通过这两种方法调用超类的构造函数时,传递和不传递自我之间会有区别。 并且如果存在差异,为什么在使用类名的情况下我们甚至通过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()

0 个答案:

没有答案