抽象基类的作用就是,让父类中的方法不可实例化,只能继承。但子类想要继承父类中的方法必须
实现该方法,看如下代码。

代码

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

执行

[root@localhost 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()

执行

[root@localhost nova]# python test.py 
From Fish
This is Carp!
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐