内容简介:
和Java一样,Python语言支持抽象类。抽象类用于被继承,而不能被实例化。
抽象类至少有一个抽象方法。所谓抽象方法,在抽象类中,只有声明,没有具体实现,具体实现必须在子类中,或者说,子类需要实现抽象类中的抽象方法。
举例:
Persion是抽象类,play是抽象方法;
Boy和Girl是具体类。
#!/usr/bin/python3
# -*- coding: UTF-8 -*-
from abc import ABC, abstractmethod
#Persion类
class Persion(ABC):
__age = 1;
__sex = True; #True:男; False:女
# def __init__(self,age_param,sex_param):
# print("constructor2");
# self.__age = age_param;
# self.__sex = sex_param;
def getAge(self):
return self.__age;
def getSex(m):
return m.__sex;
def sayHello(self):
print("hello world!");
def __printHi(self):
print("Hi !!!");
@abstractmethod
def play(self):
pass
class Boy(Persion):
__name = '';
def setName(self,name):
self.__name = name;
def getName(self):
return self.__name;
def play(self):
print("I am boy, play game!");
class Girl(Persion):
__name = '';
def setName(self,name):
self.__name = name;
def getName(self):
return self.__name;
def play(self):
print("I am girl,play star!");
#error:Traceback (most recent call last):
# File "AbsPersion.py", line 50, in <module>
# p = Persion();
#TypeError: Can't instantiate abstract class Persion with abstract methods play
#p = Persion();
#p.getName();
boy = Boy();
boy.play();
girl = Girl();
girl.play();
运行结果:
python3 AbsPersion.py
I am boy, play game!
I am girl,play star!
说明:
使用ABC作为抽象类的基类,用@abstractmethod对抽象方法进行注解。
而对于下面的代码,就会出错:
p = Persion();
p.getName();
错误提示:
Traceback (most recent call last):
File "AbsPersion.py", line 50, in <module>
p = Persion();
TypeError: Can't instantiate abstract class Persion with abstract methods play
即不能实例化一个带有抽象方法play的抽象类Persion。