支持细粒度控制对象创建和初始化的MetaClass
项目描述
metaframe
metaframe元类基础设施,用于拦截实例创建/初始化,允许修改args/kwargs和实例。
文档
在readthedocs.org上阅读完整文档
Python 2/3支持
Python 2.7
Python 3.2/3.3/3.4/3.5
它还可以与pypy和pypy3一起工作
安装
metaframe是自包含的,没有外部依赖项
从PyPI安装
pip install metaframe
从源代码安装
将源代码中找到的
目录放置在您的项目内
功能
MetaFrame元类适用于任何对象 - 嵌入静态方法_with_class以启用继承
MetaFrameBase类,类可以从它继承
3个钩子(类方法)
_new_pre:在对象创建之前调用
_new_do:用于对象创建
_init_pre:在对象创建/初始化之前调用
_init_do:用于对象初始化
_init_post:在对象初始化之后调用
用法
一个快速示例,在对象创建之前从kwargs中过滤掉None和不能转换为float的参数
from metaframe import MetaFrame class A(MetaFrame.as_metaclass(object)): @classmethod def _new_do(cls, *args, **kwargs): nkwargs = dict() for key, val in kwargs.items(): # Remove any argument with a value of None if val is None: continue try: val = float(val) except: continue nkwargs[key] = val # The only nuisance being the cumbersome call to _new_do # super doesn't work obj, args, kwargs = cls.__class__._new_do(cls, *args, **nkwargs) return obj, args, kwargs def __init__(self, **kwargs): for key, val in kwargs.items(): print('key, val, type', key, val, type(val)) a = A(p1=72, p2=None, p3='hello', p4=None, p5='72.5') # Now with a subclassed MetaB from MetaFrame # Here super can be applied to find the higher in the hierarchy _new_do class MetaB(MetaFrame): def _new_do(cls, *args, **kwargs): nkwargs = dict() for key, val in kwargs.items(): # Remove any argument with a value of None if val is None: continue try: val = float(val) except: continue nkwargs[key] = val # super can be called directly obj, args, kwargs = super(MetaB, cls)._new_do(*args, **nkwargs) return obj, args, kwargs class B(MetaB.as_metaclass()): def __init__(self, **kwargs): for key, val in kwargs.items(): print('key, val, type', key, val, type(val)) b = B(p1=27, p2=None, p3='olleh', p4=None, p5='5.27')
项目详情
关闭
metaframe-1.0.1.zip的哈希值
算法 | 哈希摘要 | |
---|---|---|
SHA256 | 336c564ad36e081eb1fef896683d13ae4af2c428cf0db08432e10b000840192b |
|
MD5 | b8148957beeee8537326ce340e692073 |
|
BLAKE2b-256 | 112cc2d55ddc1dc85d60a263d8f66552dbe117c4e332f5fa594bdd0fd4918bbc |