类继承

作者: mysimplebook | 来源:发表于2019-11-13 13:51 被阅读0次

继承是相对两个类而言的父子关系,在Python中,可以让一个类去继承一个类,被继承的类称为父类或者超类、也可以称作基类,继承的类称为子类。并且Python支持多继承,能够让一个子类有多个父类。在定义一个类的时候,可以在类名后面紧跟一对括号,在括号中指定所继承的父类,如果有多个父类,多个父类名之间用逗号隔开。

在Python中,同时支持单继承与多继承,语法如下:

class SubClassName(ParentClass1 [,ParentClass2, ...]):

class_suite

通过继承,子类实例同样也是父类的实例。

子类继承了父类什么

如下一个继承关系

class Person:

   """this is father"""

   country="earth";                                        #类变量

   def __init__(self,namepara,agepara):                #实例属性一般通过__init__方法初始化

        self.name=namepara                     #初始化self.name,即成员变量name

        self.age=agepara

                                       

   def selfmethod(self):

        print("my name is"+self.name)                

   

   @classmethod

   def clsmethod(cls):

        print("father's classmethod")

 

class SubPerson(Person):                       #继承父类Person

       

   def subselfmethod(self):                                #重写父类的innerfun方法

        print ("SubPerson's instancemethod")

   @classmethod

   def subclsmethod(cls):

        print("subclass's method")

         使用dir函数查看一下各类的属性

>>> dir(Person)

['__class__', '__delattr__','__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__','__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__','__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__','__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__','__subclasshook__', '__weakref__','clsmethod',

'country', 'selfmethod']

>>> dir(SubPerson)

['__class__', '__delattr__','__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__','__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__','__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__','__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__','__subclasshook__', '__weakref__','clsmethod',

'country', 'selfmethod', 'subclsmethod', 'subselfmethod']

>>> 

可见,对于继承关系,子类继承了父类所有的类数据属性和方法属性。__init__()方法也只是一个普通的实例方法,继承发生的时候,父类的__init__方法也会被继承。

因为类中同名的方法或类属性将覆盖类中排在其上面的同名方法或类属性,所以如果子类中定义了同名方法(无论是重写或重载),子类都将无法使用父类中的方法。

如改写SubPerson类为

classSubPerson(Person):                       #继承父类Person

   

    country="china"

    def __init__(self, sex):             #

       self.sex = sex

       

    def subselfmethod(self):                              

        print ("SubPerson's instancemethod")

    @classmethod

    def subclsmethod(cls):

        print("subclass's method")

   

    def selfmethod(self,otherpara):

        print("overload father'sinstancemethod "+otherpara)

   

    @classmethod

    def clsmethod(cls):

        print("overwrite father's classmethod")

测试结果有

>>>sp=SubPerson('m')

>>>sp.selfmethod()

Traceback(most recent call last):

  File "", line 1, in

TypeError:selfmethod() missing 1 required positional argument: 'otherpara'

>>>

>>>sp.clsmethod()

overwritefather's class method

>>>sp.country

'china'

>>> 

文档字符串对于类、函数/方法,以及模块来说是唯一的,也就是说doc属性是不能从父类中继承来的。如

>>>Person.__doc__

'this isfather'

>>>SubPerson.__doc__

>>> 

单继承中调用父类方法

如上所述,子类中同名的方法会覆盖父类中的同名方法,如果子类想要继承父类方法体的同时,并扩展该方法体,这就需要在子类方法中显式调用父类的方法。

子类调用父类的方法的方式有两种:

1、父类名.父类方法名(参数列表)

2、super(子类类名,self).父类方法名(参数列表) 或super().父类方法名(参数列表)

上面第二种方法在python2中的话,你要这样用。在python3里可以这样用super().父类方法名(参数列表)。super的作用是避免硬编码,通过父类名直接访问父类的属性,需要经父类名硬编码到子类中,为了解决这个问题,可以使用Python中的super关键字,super主要来调用父类方法来显式调用父类。

classSubPerson(Person):                      #继承父类Person

   

    country="china"

    def __init__(self, name, age, sex):             #

        Person.__init__(self, name, age)           #显式调用父类初始化方法

        self.sex = sex

       

    def subselfmethod(self):                              

        super().selfmethod()

        print ("SubPerson's instancemethod")

    @classmethod

    def subclsmethod(cls):

        print("subclass's method")

       测试用例

>>>sp=SubPerson('test',20,'m')

>>>sp.subselfmethod()

my name istest

SubPerson'sinstance method

>>> 

相关文章

  • 一阶段day16-01面向对象

    Python中类支持继承,并且支持多继承 一、继承 1、什么是继承 父类(超类):被继承的类子类:继承父类的类继承...

  • 2018-10-19面向对象和pygame

    类的继承 python中的类支持继承,并且支持多继承 1.什么是继承 父类(超类):被继承的类子类:继承的类继承就...

  • python零基础13:类的继承和定制

    类的定制和继承是什么? 类的继承 类的定制 类的继承要怎么写? 继承基础语法 继承之多层继承 继承的多重继承 类的...

  • Day16总结:面向对象和pygame

    类的继承 python中类支持继承,并且支持多继承 1.什么是继承 父类(超类):被继承的类子类:去继承父类的类继...

  • python 面向对象和pygame

    一、类的继承 python中类支持继承,并且支持多继承 1.什么是继承父类(超类):被继承的类子类:去继承父类的类...

  • 10.19 day16面向对象和pygame

    1.类的继承python中类 支持继承,并且支持多继承()1.什么是继承父类(超类):被继承的类 子类:继承的类,...

  • Day16-面向对象和pygame

    一、类的继承 python中类支持继承,并且支持多继承 1.什么是继承 父类(超类):被继承的类 子类:去继承父类...

  • 2018-10-19继承、重写、内存管理和认识pygame

    一、类的继承 Python中类支持继承,并且支持多继承 1、什么是继承 父类(超类):被继承的类子类:去继承父类的...

  • day16

    类的继承 python中的类支持继承,并且支持多继承() 1.什么是继承 父类(超类):被继承的类子类:去继承的类...

  • day16

    一、类的继承python中类支持继承,并且支持多继承 1.什么是继承父类(超类):被继承的类子类:去继承父类的类继...

网友评论

      本文标题:类继承

      本文链接:https://www.haomeiwen.com/subject/sgmhictx.html