1. 程式人生 > 實用技巧 >python---抽象方法的簡易使用

python---抽象方法的簡易使用

#通過子類例項父類
from
abc import ABC,abstractmethod,abstractproperty class Drawable(ABC): @abstractproperty def size(self): pass @abstractmethod def draw(self,x,y,scale=1.0): pass def double_draw(self,x,y): self.draw(x,y,scale=2.0) class Circle(Drawable): def
draw(self, x, y, scale=1.0): print(x*scale,y*scale) @property def size(self): return 'Circle size' c=Circle() print(dir(c)) c.draw(1,2) c.double_draw(1,2)from abc import ABC,abstractmethod,abstractproperty

----
#output:

['__abstractmethods__', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__weakref__', '_abc_impl', 'double_draw', 'draw', 'size']

1.0 2.0
2.0 4.0

----

#父類不能直接例項呼叫
class
Drawable(ABC): @abstractproperty def size(self): pass @abstractmethod def draw(self,x,y,scale=1.0): pass def double_draw(self,x,y): self.draw(x,y,scale=2.0) class Circle(Drawable): def draw(self, x, y, scale=1.0):
print(x*scale,y*scale) @property def size(self): return 'Circle size' b=Drawable() b.draw(1,2)


----
#output:

Traceback (most recent call last):
File "D:/djangocode/Celery_ttoia/app/tests.py", line 50, in <module>
b=Drawable()
TypeError: Can't instantiate abstract class Drawable with abstract methods draw, size

----

抽象方法是父類的一個方法, 父類沒有實現這個方法, 父類是不可以例項化的. 子類繼承父類, 子類必須實現父類定義的抽象方法, 子類才可以被例項化. Python中的abc提供了@abstractmethod裝飾器實現抽象方法的定義

from abc import ABC, abstractmethod

class Foo(ABC):
    @abstractmethod
    def fun(self):
        """
        你需要在子類中實現該方法, 子類才允許被例項化
        """

class SubFoo(Foo):

    def fun(self):
        print("子類實現父類的抽象方法")
    def go(self):
        print(666)

if __name__ == "__main__":

    sf = SubFoo()
    sf.fun()
  ----
#outout:
子類實現父類的抽象方法

當子類未重寫父類fun方法時:

from abc import ABC, abstractmethod

class Foo(ABC):
    @abstractmethod
    def fun(self):
        """
        你需要在子類中實現該方法, 子類才允許被例項化
        """

class SubFoo(Foo):

    # def fun(self):
        # print("子類實現父類的抽象方法")
    def go(self):
        print(666)

if __name__ == "__main__":

    sf = SubFoo()
    sf.go()
----
#output:
Traceback (most recent call last):
  File "D:/djangocode/Celery_ttoia/app/tests.py", line 122, in <module>
    sf = SubFoo()
TypeError: Can't instantiate abstract class SubFoo with abstract methods fun
----