我有这个代码:
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
如果你想在使用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)
| 归档时间: |
|
| 查看次数: |
47 次 |
| 最近记录: |