作者: seven1010 | 来源:发表于2018-07-13 10:11 被阅读12次
    • 子类将继承父类所有的方法和属性吗?为什么?

      • 子类不能继承父类的所有方法和属性,只能继承父类所有的非private(私有)的属性和方法,而private成员是不能被继承的。
    • 类方法的变量不加self,也就是xxx,这个是方法的局部变量,不能被调用,只能在该方法内部使用!

    • 类的私有属性:__private_attrs 两个下划线开头,声明该属性为私有,不能在类的外部被使用或直接访问。在类内部的方法中使用时 self.__private_attrs

    • 先回顾下 OOP 的常用术语:

    类:对具有相同数据和方法的一组对象的描述或定义。
    对象:对象是一个类的实例。
    实例(instance):一个对象的实例化实现。
    实例属性(instance attribute):一个对象就是一组属性的集合。
    实例方法(instance method):所有存取或者更新对象某个实例一条或者多条属性的函数的集合。
    类属性(classattribute):属于一个类中所有对象的属性,不会只在某个实例上发生变化
    类方法(classmethod):那些无须特定的对象实例就能够工作的从属于类的函数。
    
    • 类的专有方法
    __init__       构造函数,在生成对象时调用
    __del__        析构函数,释放对象时使用
    __repr__       打印,转换
    __setitem__    按照索引赋值
    __getitem__    按照索引获取值
    __len__        获得长度
    __cmp__        比较运算
    __call__       函数调用
    __add__        加运算
    __sub__        减运算
    __mul__        乘运算
    __div__        除运算
    __mod__        求余运算
    __pow__        称方
    
    • 类数据属性和实例数据属性
    类数据属性属于类本身,可以通过类名进行访问/修改
    类数据属性也可以被类的所有实例访问
    在类定义之后,可以通过类名动态添加类数据属性,新增的类属性也被类和所有实例共有
    实例数据属性只能通过实例访问/修改
    在实例生成后,还可以动态添加实例数据属性,但是这些实例数据属性只属于该实例
    
    • 特殊的类属性:对于所有类,都有一组特殊属性
    _ _ name_ _:类的名字(字符串)
    _ _ doc _ _ :类的文档字符串
    _ _ bases _ _:类的所有父类组成的元组
    _ _ dict _ _:类的属性组成的字典
    _ _ module _ _:类所属的模块
    _ _ class _ _:类对象的类型
    

    继承

    • 实现继承之后,子类将继承父类的属性,也可以使用内建函数insubclass()来判断一个类是不是另一个类的子孙类

    通过之前四篇的介绍:

    • 【python】python中的类,对象,方法,属性初认识(一)详见链接
    • 【python】详解类class的属性:类数据属性、实例数据属性、特殊的类属性、属性隐藏(二)详见链接
    • 【python】详解类class的方法:实例方法、类方法、静态方法(三)详见链接
    • 【python】详解类class的访问控制:单下划线与双下划线_(四)详见链接

    Python中类相关的一些基本点已经比较完整清晰了,本文继续深入Python中类的继承和_ _slots _ _属性。

    1、继承

    • 在Python中,同时支持单继承与多继承,一般语法如下:
    class SubClassName(ParentClass1 [, ParentClass2, ...]):
        class_suite
    
    • 实现继承之后,子类将继承父类的属性,也可以使用内建函数insubclass()来判断一个类是不是另一个类的子孙类
    # -*- coding: utf-8 -*-
    """
    Created on Sun Jan 21 22:33:09 2018
    
    @author: BruceWong
    """
    
    class Parent(object):
        '''
        parent class
        '''
        numList = []
        def numdiff(self, a, b):
            return a-b
    
    class Child(Parent):
        pass
    
    c = Child()    
    # subclass will inherit attributes from parent class 
    #子类继承父类的属性   
    Child.numList.extend(range(10))
    print(Child.numList)
    
    print("77 - 2 =", c.numdiff(77, 2))
    
    # built-in function issubclass() 
    print(issubclass(Child, Parent))
    print(issubclass(Child, object))
    
    # __bases__ can show all the parent classes
    #bases属性查看父类
    print('the bases are:',Child.__bases__)
    
    # doc string will not be inherited
    #doc属性不会被继承
    print(Parent.__doc__)
    print(Child.__doc__)
    

    代码的输出为:

    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    77 - 2 = 75
    True
    True
    the bases are: (<class '__main__.Parent'>,)
    
        parent class
    
    None
    

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

    2、继承中的_ init _**
    当在Python中出现继承的情况时,一定要注意初始化函数init的行为:**

    • 如果子类没有定义自己的初始化函数,父类的初始化函数会被默认调用;但是如果要实例化子类的对象,则只能传入父类的初始化函数对应的参数,否则会出错。
    • 如果子类定义了自己的初始化函数,而在子类中没有显示调用父类的初始化函数,则父类的属性不会被初始化
    • 如果子类定义了自己的初始化函数,在子类中显示调用父类,子类和父类的属性都会被初始化

    2.1、子类没有定义自己的初始化函数,父类的初始化函数会被默认调用:

    #定义父类:Parent
    class Parent(object):
        def __init__(self, name):
            self.name = name
            print("create an instance of:", self.__class__.__name__)
            print("name attribute is:", self.name)
    #定义子类Child ,继承父类Parent       
    class Child(Parent):
        pass
    #子类实例化时,由于子类没有初始化,此时父类的初始化函数就会默认被调用
    #且必须传入父类的参数name
    c = Child("init Child") 
    

    子类实例化时,由于子类没有初始化,此时父类的初始化函数就会默认被调用,此时传入父类的参数name,输出结果为:

    create an instance of: Child
    name attribute is: init Child
    

    如果不传入父类的参数name:

    class Parent(object):
        def __init__(self, name):
            self.name = name
            print("create an instance of:", self.__class__.__name__)
            print("name attribute is:", self.name)
    
    class Child(Parent):
        pass
    
    #c = Child("init Child") 
    #print()    
    c = Child()
    

    没有传入父类name参数的输出结果会报错:

    Traceback (most recent call last):
    
      File "<ipython-input-11-9a7781a6f192>", line 1, in <module>
        runfile('C:/Users/BruceWong/.spyder-py3/类的继承.py', wdir='C:/Users/BruceWong/.spyder-py3')
    
      File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
        execfile(filename, namespace)
    
      File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
        exec(compile(f.read(), filename, 'exec'), namespace)
    
      File "C:/Users/BruceWong/.spyder-py3/类的继承.py", line 54, in <module>
        c = Child()
    
    TypeError: __init__() missing 1 required positional argument: 'name'
    

    2.2、子类定义了自己的初始化函数,而在子类中没有显示调用父类的初始化函数,则父类的属性不会被初始化

    class Parent(object):
        def __init__(self, name):
            self.name = name
            print("create an instance of:", self.__class__.__name__)
            print("name attribute is:", self.name)
    #子类继承父类        
    class Child(Parent):
        #子类中没有显示调用父类的初始化函数
        def __init__(self):
            print("call __init__ from Child class")
    #c = Child("init Child") 
    #print()  
    #将子类实例化  
    c = Child()
    print(c.name)
    

    在子类中没有显示调用父类的初始化函数,则父类的属性不会被初始化,因而此时调用子类中name属性不存在:
    AttributeError: ‘Child’ object has no attribute ‘name’

    call __init__ from Child class
    Traceback (most recent call last):
    
      File "<ipython-input-12-9a7781a6f192>", line 1, in <module>
        runfile('C:/Users/BruceWong/.spyder-py3/类的继承.py', wdir='C:/Users/BruceWong/.spyder-py3')
    
      File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 866, in runfile
        execfile(filename, namespace)
    
      File "C:\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
        exec(compile(f.read(), filename, 'exec'), namespace)
    
      File "C:/Users/BruceWong/.spyder-py3/类的继承.py", line 56, in <module>
        print(c.name)
    
    AttributeError: 'Child' object has no attribute 'name'
    

    2.3、如果子类定义了自己的初始化函数,显示调用父类,子类和父类的属性都会被初始化

    class Parent(object):
        def __init__(self, name):
            self.name = name
            print("create an instance of:", self.__class__.__name__)
            print("name attribute is:", self.name)
    
    class Child(Parent):
        def __init__(self):
            print("call __init__ from Child class")
            super(Child,self).__init__("data from Child")   #要将子类Child和self传递进去
    #c = Child("init Child") 
    #print() 
    d = Parent('tom')   
    c = Child()
    print(c.name)
    

    子类定义了自己的初始化函数,显示调用父类,子类和父类的属性都会被初始化的输出结果:

    #实例化父类Parent的结果
    create an instance of: Parent
    name attribute is: tom
    
    #实例化子类Child的结果
    call __init__ from Child class
    #super首先会先使得父类初始化的参数进行实例化
    create an instance of: Child
    name attribute is: data from Child
    data from Child
    

    3、super的使用详解

    • super主要来调用父类方法来显示调用父类,在子类中,一般会定义与父类相同的属性(数据属性,方法),从而来实现子类特有的行为。也就是说,子类会继承父类的所有的属性和方法,子类也可以覆盖父类同名的属性和方法
    class Parent(object):
        Value = "Hi, Parent value"
        def fun(self):
            print("This is from Parent")
    #定义子类,继承父类               
    class Child(Parent):
        Value = "Hi, Child  value"
        def ffun(self):
            print("This is from Child")
    
    c = Child()    
    c.fun()
    c.ffun()
    print(Child.Value)
    

    输出结果:

    This is from Parent
    This is from Child
    Hi, Child value
    

    但是,有时候可能需要在子类中访问父类的一些属性,可以通过父类名直接访问父类的属性,当调用父类的方法是,需要将”self”显示的传递进去的方式

    class Parent(object):
        Value = "Hi, Parent value"
        def fun(self):
            print("This is from Parent")
    
    class Child(Parent):
        Value = "Hi, Child  value"
        def fun(self):
            print("This is from Child")
            Parent.fun(self)   #调用父类Parent的fun函数方法
    
    c = Child()    
    c.fun()
    

    输出结果:

    This is from Child
    This is from Parent  #实例化子类Child的fun函数时,首先会打印上条的语句,再次调用父类的fun函数方法
    

    这种方式有一个不好的地方就是,需要经父类名硬编码到子类中,为了解决这个问题,可以使用Python中的super关键字:

    class Parent(object):
        Value = "Hi, Parent value"
        def fun(self):
            print("This is from Parent")
    
    class Child(Parent):
        Value = "Hi, Child  value"
        def fun(self):
            print("This is from Child")
            #Parent.fun(self)
            super(Child,self).fun()  #相当于用super的方法与上一调用父类的语句置换
    
    c = Child()    
    c.fun()
    

    输出结果:

    This is from Child
    This is from Parent  #实例化子类Child的fun函数时,首先会打印上条的语句,再次调用父类的fun函数方法
    

    相关文章

      网友评论

          本文标题:

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