zoukankan      html  css  js  c++  java
  • 多态和封装

    继承顺续

    1.python中的类可以继承多个类,java和c#中则只能继承一个类
    2.python的类如果继承了多个类,那么其寻找的方式有两种,分别是深度优先和广度优先
    3.在python3中所有的类都是新式类,都哦按照广度优先来寻找。
    mro表
    python3对于你定义的每一个类,python会计算出一个方法解析顺序(MRO)列表,这个MRO列表就是一个简单的所有基类的线性顺序列表

    # python2,深度优先 寻找顺序 F-->D-->B-->C-->E
    # python3:广度优先 寻找顺序 F-->D-->E-->B-->C
    class B:
        def test(self):
            print("from B")
            pass
    
    class C:
        def test(self):
            print("from C")
            pass
    
    class D(B,C):
        def test(self):
            print("from D")
            pass
    
    
    class E(B,C):
        def test(self):
            print("from E")
            pass
    
    
    class F(D, E):
        def test(self):
            print("from F")
            pass
    
    f = F()
    f.test()
    # print(F.mro()) # python3查看mro顺序表
    

    多态和多态性

    # 2.作业二:基于多态的概念来实现linux中一切皆问题的概念:文本文件,进程,磁盘都是文件,然后验证多态性
    import abc
    class All_file(metaclass=abc.ABCMeta):
        @abc.abstractmethod
        def read(self):
            print("All file")
            pass
    
        @abc.abstractmethod
        def write(self):
            print("All file")
            pass
    
    
    class Txt(All_file):
        def read(self):
            super().read()
            print("Txt read")
    
    
        def write(self):
            super().write()
            print("Txt write")
    
    
    class Sata(All_file):
        def read(self):
            super().read()
            print("Sata read")
    
    
        def write(self):
            super().write()
            print("Sata write")
    
    
    def read(obj):
        obj.read()
    
    
    def write(obj):
        obj.write()
    
    t = Txt()
    s = Sata()
    t.read()
    s.write()
    read(s)
    

    封装

    在python中用双下划线的方式实现隐藏属性(设置成私有的)

    class A:
        __N=0 #类的数据属性就应该是共享的,但是语法上是可以把类的数据属性设置成私有的如__N,会变形为_A__N
        def __init__(self):
            self.__X=10 #变形为self._A__X
        def __foo(self): #变形为_A__foo
            print('from A')
        def bar(self):
            self.__foo() #只有在类内部才可以通过__foo的形式访问到.
    
  • 相关阅读:
    记录Integer比较问题
    代码中获取git输出
    python open mode
    elasticsearch Unrecognized VM option 'UseParNewGC'
    应用商店显示无法加载页面 请稍后重试
    deep learning with python前五章笔记
    QWeb2: Template 'systray_odoo_referral.gift_icon' not found
    wifi scapy
    struct.pack, struct.unpack详解
    python f-string
  • 原文地址:https://www.cnblogs.com/zouruncheng/p/6740367.html
Copyright © 2011-2022 走看看