首页 > 解决方案 > Python 元类:使用 class.__init__ 的参数来修改元类中的类

问题描述

我目前正试图围绕元类解决一个特定问题: - 容器类需要从其元素中公开一些功能 - 之后不能修改容器类

元类似乎是完成上述任务的好方法(例如__slots__,可以在__new__.

例子:

import inspect

class MyMeta(type):
    def __new__(cls, name, bases, attrs):
        ...
        # modify slots ?
        return super().__new__(cls, name, bases, attrs)

    def __call__(cls, *args, **kwargs):
        name = args[0]
        elements = args[1]

        tmp_class = super().__call__(*args, **kwargs)
        ds_methods = [m for m, _ in inspect.getmembers(tmp_class, predicate=inspect.ismethod)]
        e_methods = [m for m, _ in inspect.getmembers(elements[0], predicate=inspect.ismethod) if m not in ds_methods]

        attrs = {m:f for m, f in inspect.getmembers(cls, predicate=inspect.ismethod)}
        # for testing map to print
        new_attr = {m: print for m in e_methods}
        attrs.update(new_attr)
        .... # call __new__?
        # this does not contain the new methods
        newclass =  cls.__new__(cls, cls.__name__, [object], attrs)


class Container(metaclass=MyMeta):
    __slots__ = ['_name', '_elements']
    def __init__(self, name, elements):
         self._name = name
         self._elements = elements

简而言之:我发现修改插槽__new__的唯一方法是 in ,而拦截创建参数的唯一方法是 in __call__

可能有一种更简单的方法可以实现这一点(上述方法不起作用),我将感谢任何能帮助我更好地理解元类的指针。

标签: pythonmetaclass

解决方案


推荐阅读