Python抽象和自定义类定义与用法示例

yipeiwu_com6年前Python基础

本文实例讲述了Python抽象和自定义类定义与用法。分享给大家供大家参考,具体如下:

抽象方法

class Person():
  def say(self):
    pass
class Student(Person):
  def say(self):
    print("i am student")

抽象类: 包含抽象方法的类

  • 抽象类可以包含非抽象方法
  • 抽象类可以有方法和属性
  • 抽象类不能进行实例化
  • 必须继承才能使用,且继承的子类必须实现所有抽象方法
import abc
class Person(metaclass=abc.ABCMeta):
  @abc.abstractmethod
  def say(self):
    pass
class Student(Person):
  def say(self):
    print("i am student")
s = Student()
s.say()

补充:函数名和当做变量使用

class Student():
  pass
def say(self):
  print("i am say")
s = Student()
s.say=say
s.say(9)

组装类

from types import MethodType
class Student():
  pass
def 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):
  pass
t = 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面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

关于python字符串方法分类详解

关于python字符串方法分类详解

python字符串方法分类,字符串是经常可以看到的一个数据储存类型,我们要进行字符的数理,就需要用各种的方法,这里有许多方法,我给大家介绍比较常见的重要的方法,比如填充、删减、变形、分切...

Python原始字符串与Unicode字符串操作符用法实例分析

Python原始字符串与Unicode字符串操作符用法实例分析

本文实例讲述了Python原始字符串与Unicode字符串操作符用法。分享给大家供大家参考,具体如下: #coding=utf8 ''''' 在原始字符串里,所有的字符串都是直接按照...

Python全局锁中如何合理运用多线程(多进程)

Python全局锁中如何合理运用多线程(多进程)

Python全局锁 (1)全局锁导致的问题 全局锁的英文简称是GIL,全称是Global Interpreter Lock(全局解释器锁),来源是python设计之初的考虑,为了数据安全...

Python利用pandas处理Excel数据的应用详解

Python利用pandas处理Excel数据的应用详解

最近迷上了高效处理数据的pandas,其实这个是用来做数据分析的,如果你是做大数据分析和测试的,那么这个是非常的有用的!!但是其实我们平时在做自动化测试的时候,如果涉及到数据的读取和存储...

PyCharm在新窗口打开项目的方法

PyCharm在新窗口打开项目的方法

File->Setting 找到Appearance & Behavior -->System Setting,在右边窗口中选择 Open project in new wi...