这两个不同代码块有撒区别,最后的结果是一样的啊
class A(object):
def __init__(self, name):
self.name=name
print ("name:", self.name)
def getName(self):
return 'A ' + self.name
class B(A):
def __init__(self, name):
print ("hi")
self.name = name
def getName(self):
return 'B '+self.name
if __name__=='__main__':
b=B('hello')
print( b.getName())
#di二ge
class A(object):
def __init__(self, name):
self.name=name
print ("name:", self.name)
def getName(self):
return 'A ' + self.name
class B(A):
def __init__(self, name):
super(B, self).__init__(name)
print ("hi")
self.name = name
def getName(self):
return 'B '+self.name
if __name__=='__main__':
b=B('hello')
print (b.getName())
How can the final result be the same?
The first result is:
hi
B hello
The second result is:
('name:', 'hello')
hi
B hello
The second one calls A.__init__("hello") of the parent class, while the first one overrides the __init__(self, name) function of the parent class.