python中子类父类继承具体指什么 是指第二个类的参数是第一个类吗,加于不加有什么区别呢
PHPz
PHPz 2017-04-18 10:21:28
0
1
572

这两个不同代码块有撒区别,最后的结果是一样的啊

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())
PHPz
PHPz

学习是最好的投资!

reply all(1)
Ty80

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template