python中元类的介绍
2015-09-18 14:28
661 查看
元类MetaClass
元类是可以让你定义某些类是如何被创建的。从根本上说,赋予你如何创建类的控制权。
元类也是一个类,是一个type类。
元类一般用于创建类。在执行类定义时,解释器必须要知道这个类的正确的元类,如果此属性
没有定义,它会向上查找父类中的__metaclass__属性。如果还没发现,就查找全局变量。
对于传统类来说,它们的元类是types.ClassType。
元类也有构造器,传递三个参数:类名,从基类继承数据的元组,和类属性字典
下面我们来定义一个元类,要求写类的时候必须给类提供一个__str__()方法,如果没有提供__repr__()方法,
则给你警告。
from warnings import warn
#元类需要继承type类
class ReqStrSugRepr(type):
def __init__(cls, name, bases, attrd):
#构造函数需要传递的参数为类名,基类,类属性字典
super(ReqStrSugRepr, cls).__init__(name, bases, attrd)
# 判断__str__字符串是否在类的属性字典里
if '__str__' not in attrd:
raise TypeError('Class
requires overriding of __str__()')
if '__repr__' not in attrd:
warn('Class suggests overriding of __repr__()\n', stacklevel=3)
class Foo(object):
#给类指定元类
__metaclass__ = ReqStrSugRepr
def foo(self):
pass
#这一段代码不用创建类来测试,直接运行一下就会报错,可见元类的功力。
原文:http://www.cnblogs.com/btchenguang/archive/2012/08/27/2659369.html
相关文章推荐
- python 点滴
- python2.7+django1.8+mysql的模版显示数据的例子
- python pip国内镜像
- python中inspect使用
- python filter()、map()、reduce()函数解析
- 主要是要实现tornado实现计划任务类crontab间隔
- Python3.5 右键没有Edit with IDLE选项
- ubuntu12.04 set python-pandas
- Python opencv2 人脸识别
- 30个Python实用技巧
- [LeetCode]题解(python):014-Longest Common Prefix
- [LeetCode]题解(python):013-Roman to Integer
- Python的包管理工具Pip
- Flask 中的路由与反向路由
- python Exception
- python处理字符串
- 转载:15个最受欢迎的Python开源框架
- Python: Ubuntu 安装numpy,scipy,matplotlib
- Python线程
- Python闭包与函数对象