本文实例讲述了Python抽象和自定义类定义与用法。分享给大家供大家参考,具体如下:
抽象方法
class Person(): def say(self): passclass Student(Person): def say(self): print("i am student")
抽象类: 包含抽象方法的类
- 抽象类可以包含非抽象方法
- 抽象类可以有方法和属性
- 抽象类不能进行实例化
- 必须继承才能使用,且继承的子类必须实现所有抽象方法
import abcclass Person(metaclass=abc.ABCMeta): @abc.abstractmethod def say(self): passclass Student(Person): def say(self): print("i am student")s = Student()s.say()
补充:函数名和当做变量使用
class Student(): passdef say(self): print("i am say")s = Student()s.say=says.say(9)
组装类
from types import MethodTypeclass Student(): passdef say(self): print("i am say")s = Student()s.say=MethodType(say,Student)s.say()
元类
# 类名一般为MetaClass结尾class StudentMetaClass(type): def __new__(cls, *args, **kwargs): print("元类") return type.__new__(cls, *args, **kwargs)class Teacher(object, metaclass=StudentMetaClass): passt = Teacher()print(t.__dict__)
附:python 抽象类、抽象方法的实现示例
由于python 没有抽象类、接口的概念,所以要实现这种功能得abc.py 这个类库,具体方式如下
from abc import ABCMeta, abstractmethod#抽象类class Headers(object): __metaclass__ = ABCMeta def __init__(self): self.headers = '' @abstractmethod def _getBaiduHeaders(self):pass def __str__(self): return str(self.headers) def __repr__(self): return repr(self.headers)#实现类class BaiduHeaders(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'] return headers
如果子类不实现父类的_getBaiduHeaders
方法,则抛出TypeError: Can't instantiate abstract class BaiduHeaders with abstract methods 异常
希望本文所述对大家Python程序设计有所帮助。
注:相关教程知识阅读请移步到python教程频道。