【python】继承

继承的定义

面向对象编程 (OOP) 语言的一个主要功能就是“继承”。继承是指这样一种能力:它可以使用现有类的所有功能,并在无需重新编写原来的类的情况下对这些功能进行扩展

 

例如:

class Person(object): 
    def talk(self):
        print("person is talking...")  
 
class Chinese(Person):
    def walk(self):
        print('person is walking...')
 
c = Chinese()
c.talk()      # 调用继承的Person类的方法
c.walk()     # 调用本身的方法

输出:

 

person is talking...
people is walking...
 

 

继承中的构造函数

如果在子类中需要父类的构造方法就需要显式地调用父类的构造方法,或者不重写父类的构造方法。子类不重写 __init__,实例化子类时,会自动调用父类定义的 __init__

class Father(object):
    def __init__(self, name):
        self.name = name
        print ("name: %s" %( self.name))

    def getName(self):
        return 'Father ' + self.name
 
class Son(Father):

    def getName(self):
        return 'Son '+self.name
 
if __name__=='__main__':
    son = Son('runoob')
    print(son.getName())

输出:

name: runoob
Son runoob

 

如果重写了__init__ 时,实例化子类,就不会调用父类已经定义的 __init__,语法格式如下:

class Father(object):
    def __init__(self, name):
        self.name = name
        print ("name: %s" %( self.name))

    def getName(self):
        return 'Father ' + self.name
 
class Son(Father):
    def __init__(self, name):
        print ("hi")
        self.name =  name

    def getName(self):
        return 'Son '+self.name
 
if __name__ == '__main__':
    son = Son('runoob')
    print (son.getName())

输出:

hi
Son runoob

 

 

如果重写了__init__ 时,要继承父类的构造方法,可以使用 super 关键字:

super(子类,self).__init__(参数1,参数2,....)

还有一种经典写法:

父类名称.__init__(self,参数1,参数2,...)

例如:

class Father(object):
    def __init__(self, name):
        self.name=name
        print ( "name: %s" %( self.name))

    def getName(self):
        return 'Father ' + self.name
 
class Son(Father):
    def __init__(self, name):
        super(Son, self).__init__(name)
        print ("hi")
        self.name = name

    def getName(self):
        return 'Son '+self.name
 
if __name__ == '__main__':
    son = Son('runoob')
    print (son.getName())

输出:

name: runoob
hi
Son runoob

 

子类对父类方法的重写

如果我们对基类/父类的方法需要修改,可以在子类中重构该方法。如下的talk()方法:

class Person(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age
        self.weight = 'weight'
 
    def talk(self):
        print("person is talking....")
 
class Chinese(Person):
    def __init__(self, name, age, language): 
        Person.__init__(self, name, age) 
        self.language = language
        print(self.name, self.age, self.weight, self.language)
 
    def talk(self):  # 子类 重构方法
        print('%s is speaking chinese' % self.name)
 
    def walk(self):
        print('is walking...')
 
c = Chinese('bigberg', 22, 'Chinese')
c.talk()

输出:

bigberg 22 weight Chinese
bigberg is speaking chinese

 

posted @ 2023-06-02 15:29  苏格拉底的落泪  阅读(6)  评论(0编辑  收藏  举报