我目前正试图针对某个特定问题来围绕元类: -容器类需要从其元素中公开一些功能 -之后无法修改容器类
元类似乎是完成上述任务的好方法(例如,可以在__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__
中,而截取创建参数的唯一方法是在__call__
中。
可能有一种更简单的方法来完成此操作(上面的方法不起作用),我将感谢任何有助于我更好地理解元类的指针。