Python第八周 學習筆記(1)

來源:互聯網
上載者:User

標籤:學習筆記

繼承
  • 基本概念個體繼承自父母,繼承了父母的一部分特徵,但也可以有自己的個性
  • 子類繼承了父類,就直接擁有了父類的屬性和方法,也可以定義自己的屬性、方法,甚至對父類的屬性、方法進行重寫
Python繼承實現
  • class Cat(Animal) 括弧中為該類的父類列表

  • 如果類定義時沒有父類列表,則只繼承object類
  • object類是所有類的祖先類
類的特殊屬性與方法
  • base
    • 類的基類
  • bases
    • 類的基類的元組
  • mro
    • 方法解析時的類的尋找順序,返回元組
  • mro()
    • 作用同上,返回列表
  • subclasses()
    • 返回類的子類的列表
Python繼承中的注意事項
  • 屬於父類的私人成員,子類即使與父類存在繼承關係也不可直接存取(可通過改名後的屬性名稱訪問,但慎用)
  • 例子:
class Animal:    __count=100    heigtht=0    def showcount3(self):        print(self.__count)class Cat(Animal):    name=‘cat‘    __count=200c=Cat()c.showcount3()

結果為100

因為子類調用了父類擷取父類私人變數的方法 self.count的count範圍是在父類下的,其真正調用的self._Animal__count,而這個屬性只有父類有

  • 解決的辦法:自己私人的屬性,用自己的方法讀取和修改,不要藉助其他類的方法,即使是父類或衍生類別的方法
屬性尋找順序
  • 執行個體dict -> 類dict -> 父類dict
多繼承
  • 一個類繼承自多個類就是多繼承,他將具有多個類的特徵

  • 多繼承容易引起二義性,為此Python3利用C3演算法產生MRO有序列表解決多繼承的二義性(拓撲排序)
    https://kevinguo.me/2018/01/19/python-topological-sorting/#%E4%B8%80%E4%BB%80%E4%B9%88%E6%98%AF%E6%8B%93%E6%89%91%E6%8E%92%E5%BA%8F
Mixin
  • 本質是多繼承
  • 體現的是一種組合的設計模式
Mixin類使用原則
  • 類中不應該顯示的出現init初始化方法
  • 通常不能獨立工作,因為它是準備混入別的類中的部分功能實現
    其祖先類也應是Mixin類

  • 使用Mixin時,其通常在繼承列表的第一個位置

  • 裝飾器實現
def printable(cls):    def _print(self):        print(self.content, ‘decorator‘)    cls.print = _print    return clsclass Document:    def __init__(self, content):        self.content = contentclass Word(Document):    passclass Pdf(Document):    pass@printableclass PrintableWord(Word): passprint(PrintableWord.__dict__)print(PrintableWord.mro())pw = PrintableWord(‘test string‘)pw.print()@printableclass PrintablePdf(Word):    pass
  • 優點:
    • 簡單方便,在需要的地方動態增加,直接使用裝飾器
Mixin實現
class Document:    def __init__(self, content):        self.content = contentclass Word(Document):    passclass Pdf(Document):    passclass PrintableMixin:    def print(self):        print(self.content, ‘Mixin‘)class PrintableWord(PrintableMixin, Word):    passprint(PrintableWord.__dict__)print(PrintableWord.mro())pw = PrintableWord(‘test string‘)pw.print()class SuperPrintableMixin(PrintableMixin):    def print(self):        print(‘~‘ * 20)        super().print()        print(‘~‘ * 20)class SuperPrintablePdf(SuperPrintableMixin, Pdf):    passprint(SuperPrintablePdf.__dict__)print(SuperPrintablePdf.mro())spp = SuperPrintablePdf(‘super print pdf‘)spp.print()
Mixin類和裝飾器
  • 這兩種方式都可以使用,看個人喜好
  • 如果還需要繼承就得使用Mixin類

Python第八周 學習筆記(1)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.