Python类继承

Pet*_*hao 2 python class

我有这个代码:

class A(object):
    def __init__(self):
       print " A"

class B(A):
    def __init__(self):
        print "B"
x=B()
print "Done"
Run Code Online (Sandbox Code Playgroud)

结果是:"B"被打印为什么它不打印"A",尽管B类继承A

Joh*_*024 6

如果你想在使用B的__init__同时使用A __init__,那么试试:

class A(object):
    def __init__(self):
       print " A"

class B(A):
    def __init__(self):
        A.__init__(self)
        print "B"
x=B() 
print "Done"
Run Code Online (Sandbox Code Playgroud)

或者,如果您不想按名称提及超类:

class A(object):
    def __init__(self):
       print " A"

class B(A):
    def __init__(self):
        super(B, self).__init__()
        print "B"
x=B()
print "Done"
Run Code Online (Sandbox Code Playgroud)

这两个产生输出:

 A
B
Done
Run Code Online (Sandbox Code Playgroud)