抽象基本クラスの役割は、親クラスのメソッドをインスタンス化できないようにすることであり、継承されるだけです。ただし、サブクラスが親クラスのメソッドを継承する場合は、
このメソッドを実装する必要があります。次のコードを参照してください。
コード
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!