跳转到主要内容

支持细粒度控制对象创建和初始化的MetaClass

项目描述

metaframe

PyPi Version PyPi Monthly Donwloads License Travis-ci Build Status Documentation Status Pytghon versions

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 (10.8 kB 查看哈希值)

上传时间 源代码

由以下支持