python抽象基類用法執行個體分析

來源:互聯網
上載者:User

python抽象基類用法執行個體分析

   本文執行個體講述了python抽象基類用法。分享給大家供大家參考。具體如下:

  定義抽象類別,需要使用abc模組,該模組定義了一個元類(ABCMeata),和裝飾器 @abstractmethod, @abstractproperty

  如果要執行個體化繼承了Foo 的子類,子類必須實現了Foo所有的抽象方法(跟java一樣),否則執行個體化報錯。

  抽象類別不能直接執行個體化

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

#!coding=utf-8

from abc import ABCMeta, abstractmethod, abstractproperty

class Foo:

__metaclass__ = ABCMeta

@abstractmethod

#在python3.0中 使用 class Foo(metaclass=ABCMeta)文法

def spam(self, a, b):

pass

@abstractproperty

def name(self):

pass

class Bar(Foo):

def spam(self, a, b):

print a, b

def name():

pass

b = Bar()

b.spam(1,2)

  抽象基類支援對已經存在的類進行註冊,使其屬於該基類,使用register()方法

  向抽象基類註冊某個類,對於註冊類中的執行個體,涉及後續基類的類檢測操作比如(isinstance, issubclass) 將返回True,向抽象基類註冊某個類時,不會檢查該類是否實現了任何抽象方法或特性,這種註冊過程只會影響類型檢查

  ?

1

2

3

4

class Crok(object):

def spam(self, a, c):

print "gork.span"

Foo.register(Grok)

  希望本文所述對大家的Python程式設計有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.