Python抽象和自定义类定义与用法示例
本文实例讲述了Python抽象和自定义类定义与用法。分享给大家供大家参考,具体如下:
抽象方法
classPerson():
defsay(self):
pass
classStudent(Person):
defsay(self):
print("iamstudent")
抽象类:包含抽象方法的类
- 抽象类可以包含非抽象方法
- 抽象类可以有方法和属性
- 抽象类不能进行实例化
- 必须继承才能使用,且继承的子类必须实现所有抽象方法
importabc
classPerson(metaclass=abc.ABCMeta):
@abc.abstractmethod
defsay(self):
pass
classStudent(Person):
defsay(self):
print("iamstudent")
s=Student()
s.say()
补充:函数名和当做变量使用
classStudent():
pass
defsay(self):
print("iamsay")
s=Student()
s.say=say
s.say(9)
组装类
fromtypesimportMethodType
classStudent():
pass
defsay(self):
print("iamsay")
s=Student()
s.say=MethodType(say,Student)
s.say()
元类
#类名一般为MetaClass结尾
classStudentMetaClass(type):
def__new__(cls,*args,**kwargs):
print("元类")
returntype.__new__(cls,*args,**kwargs)
classTeacher(object,metaclass=StudentMetaClass):
pass
t=Teacher()
print(t.__dict__)
附:python抽象类、抽象方法的实现示例
由于python没有抽象类、接口的概念,所以要实现这种功能得abc.py这个类库,具体方式如下
fromabcimportABCMeta,abstractmethod
#抽象类
classHeaders(object):
__metaclass__=ABCMeta
def__init__(self):
self.headers=''
@abstractmethod
def_getBaiduHeaders(self):pass
def__str__(self):
returnstr(self.headers)
def__repr__(self):
returnrepr(self.headers)
#实现类
classBaiduHeaders(Headers):
def__init__(self,url,username,password):
self.url=url
self.headers=self._getBaiduHeaders(username,password)
def_getBaiduHeaders(self,username,password):
client=GLOBAL_SUDS_CLIENT.Client(self.url)
headers=client.factory.create('ns0:AuthHeader')
headers.username=username
headers.password=password
headers.token=_baidu_headers['token']
returnheaders
如果子类不实现父类的_getBaiduHeaders方法,则抛出TypeError:Can'tinstantiateabstractclassBaiduHeaderswithabstractmethods 异常
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。