python面對對象編程---------6:抽象基類

 抽象基本類的幾大特色:python

    1:要定義可是並不完整的實現全部方法
2:基本的意思是做爲父類
3:父類須要明確表示出那些方法的特徵,這樣在寫子類時更加簡單明白

用抽象基本類的地方:
1:用做父類
2:用做檢驗實例類型
3:用做拋出異常說明

關於抽象基本類的幾點說明:
1:LSP(裏式替換原則):
子類必須可以替換他們的基類型,替換後軟件運行形態不變,覺察不出基類和子類的區別。
這樣來檢驗該設計是否合理或者藏有缺陷。(從抽象類繼承而不是具體類)

2:關於isinstance的使用:
首先:大量的isinstance檢測會形成複雜而緩慢的程序還代表多態設計很差
其次:在使用isinstance時更加pythonic的用法是處理錯誤而不是請求許可
1:請求許可:
assert isinstance( some_argument, collections.abc.Container ),"{0!r} not a Container".format(some_argument)
儘管很簡潔,可是有兩個缺點: assertions can be silenced, and it would probably be better to raise a TypeError for this:
if not isinstance(some_argument, collections.abc.Container):
raise TypeError( "{0!r} not a Container".format(some_argument))
2:處理異常
try:
found = value in some_argument
except TypeError:
if not isinstance(some_argument, collections.abc.Container):
warnings.warn( "{0!r} not a Container".format(some_argument) )
raise

3:Containers and collections
container(容器),既是其能夠包含多個對象,實際上是多個reference的集合的概念,python內置的containers有好比list,map,set.
    collections是python內建的一個集合模塊,提供了許多可用的集合類,如namedtuple,deque,defalutdict等等。
總結:container是一個抽象類而collections是繼承了container並實現了多種子類數據結構如namedtuple,deque,chainmap,counter,ordereddict,defaultdict的類的統稱

container應該實現的:
Lower-level features include Container, Iterable, and Sized.
they require a few specific methods, particularly __contains__(), __iter__(), and __len__(), respectively

collections應該實現的:
Sequence and MutableSequence: These are the abstractions of the concrete classes list and tuple. Concrete sequence implementations also include bytes and str.
          MutableMapping: This is the abstraction of dict. It extends Mapping, but there's no built-in concrete implementation of this.
          Set and MutableSet: These are the abstractions of the concrete classes,frozenset and set.
   This allows us to build new classes or extend existing classes and maintain a clear and formal integration with the rest of Python's built-in features.

python中兩大抽象基類:
  1:各類數據類型相關的collections.abc

    >>> abs(3)
    3
    >>> isinstance(abs, collections.abc.Callable)
    True數據結構

    >>> isinstance( {}, collections.abc.Mapping )
    True
    >>> isinstance( collections.defaultdict(int), collections.abc.Mapping)
    Trueapp

  

  2:數值相關的numbersssh

    >>> import numbers, decimal
    >>> isinstance( 42, numbers.Number )
    True
    >>> isinstance( 355/113, numbers.Number ) #因而可知,integer和float都是number.Number類的子類
    True
    >>> issubclass( decimal.Decimal, numbers.Number ) #decimal.Decimal是numbers.Number的子類
    True
    >>> issubclass( decimal.Decimal, numbers.Integral )
    False
    >>> issubclass( decimal.Decimal, numbers.Real )
    False
    >>> issubclass( decimal.Decimal, numbers.Complex )
    False
    >>> issubclass( decimal.Decimal, numbers.Rational )
    False

來看一個簡單的抽象類
 1 __dict__:方法名+屬性名
 2 __mro__:  包含此類全部父類的元祖
 3 >>> class aha(list):
 4        def __init__(self,value):
 5            super().__init__(value)
 6 
 7 
 8 >>> a=aha('pd')
 9 >>> a
10 ['p', 'd']
11 >>> aha.__dict__
12 mappingproxy({'__weakref__': <attribute '__weakref__' of 'aha' objects>, '__doc__': None, '__module__': '__main__', '__dict__': <attribute '__dict__' of 'aha' objects>, '__init__': <function aha.__init__ at 0x030967C8>})
13 >>> aha.__mro__
14 (<class '__main__.aha'>, <class 'list'>, <class 'object'>)
__dict__與__mro__
 1 from abc import ABCMeta, abstractmethod
 2 class AbstractBettingStrategy(metaclass=ABCMeta):
 3     __slots__ = ()
 4     @abstractmethod
 5     def bet(self, hand):
 6         return 1
 7     @abstractmethod
 8     def record_win(self, hand):
 9         pass
10     @abstractmethod
11     def record_loss(self, hand):
12         pass
13     @classmethod                                #檢查了三個用抽象方法在子類中是否implement,不然報錯。
14     def __subclasshook__(cls, subclass):
15         if cls is Hand:
16             if (any("bet" in B.__dict__ for B in subclass.__mro__) and any("record_win" in B.__dict__ for B in subclass.__mro__) and any("record_loss" in B.__dict__ for B in subclass.__mro__)):
17                 return True
18         return NotImplemented
19 
20 class Simple_Broken(AbstractBettingStrategy):
21     def bet( self, hand ):
22         return 1
23 # The preceding code can't be built because it doesn't provide necessary implementations for all three methods.
24 # The following is what happens when we try to build it:
25 >>> simple= Simple_Broken()
26 Traceback (most recent call last):
27 File "<stdin>", line 1, in <module>
28 TypeError: Can't instantiate abstract class Simple_Broken with
29 abstract methods record_loss, record_win
#注,上例可能太過嚴格,有些子類並不須要實現其全部方法,這個須要具體狀況再看
#注,此篇可能看起來有點不太邏輯清晰,這源於我對collections.abc以及number模塊目前還不太清晰,等改天研究明白了來改改,加些內容,此時先放出來佔個位
相關文章
相關標籤/搜索