Python 2 abstract base class

The role of the abstract base class is to make the methods in the parent class not instantiable but only inherited. But the subclass wants to inherit the method in the parent class must
implement this method, see the following code.

Code

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() 

carried out

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

Code

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

carried out

[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

Code

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()

carried out

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

Guess you like

Origin blog.csdn.net/weixin_40548182/article/details/111593929