python 2 抽象基类
抽象基类的作用就是,让父类中的方法不可实例化,只能继承。但子类想要继承父类中的方法必须实现该方法,看如下代码。代码cat test.py#/usr/bin/env python#coding:utf8fromabc import ABCMeta,abstractmethodclass Fish():__metaclass__ = ABCMeta@abstractmethoddef swim(sel
·
抽象基类的作用就是,让父类中的方法不可实例化,只能继承。但子类想要继承父类中的方法必须
实现该方法,看如下代码。
代码
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!
更多推荐
已为社区贡献3条内容
所有评论(0)