1. 程式人生 > 其它 >python 2 抽象基類

python 2 抽象基類

技術標籤:Pythonpython

抽象基類的作用就是,讓父類中的方法不可例項化,只能繼承。但子類想要繼承父類中的方法必須
實現該方法,看如下程式碼。

程式碼

cat test.py 
#/usr/bin/env python
#coding:utf8
from  abc import ABCMeta,abstractmethod
class Fish():
    __metaclass__ = ABCMeta
    @abstractmethod
    def swim(self):
        print '游泳'
fish = Fish()
fish.swim() 

執行

python test.
py Traceback (most recent call last): File "test.py", line 9, in <module> fish = Fish() TypeError: Can't instantiate abstract class Fish with abstract methods swim

程式碼

cat test.py 
#/usr/bin/env python
#coding:utf8
from  abc import ABCMeta,abstractmethod
class Fish():
    __metaclass__ =
ABCMeta @abstractmethod def swim(self): print '游泳' class Goldfish(Fish): def run(self): print('This is Goldfish!') gold = Goldfish() gold.run

執行

[[email protected] nova]# python test.py 
Traceback (most recent call last):
  File "test.py", line 15, in <
module> gold = Goldfish() TypeError: Can't instantiate abstract class Goldfish with abstract methods swim

程式碼

cat test.py 
#/usr/bin/env python
#coding:utf8
from  abc import ABCMeta,abstractmethod
class Fish():
    __metaclass__ = ABCMeta
    @abstractmethod
    def swim(self):
        print '游泳'

class Goldfish(Fish):
    def run(self):
        print('This is Goldfish!')

class Carp(Fish):
    def swim(self):
        print("From Fish")
    def run(self):
        print('This is Carp!')
 
carp = Carp()
carp.swim()
carp.run()

執行

[[email protected] nova]# python test.py 
From Fish
This is Carp!