python - 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__
。
可能有一种更简单的方法可以实现这一点(上述方法不起作用),我将感谢任何能帮助我更好地理解元类的指针。
解决方案
推荐阅读
- json - 如何将数据文件(xml、json、yaml)转换为可执行的 C 文件?
- python - 组的名称是什么?在 odoo 10
- spring-boot - 从 microsoft adal + spring boot 与 azure Active Directory 集成中获取组和角色信息
- ios - 如何使代码更简单,更可重用swiftui中具有多维字典的导航链接?
- go - 从类型 []primitive.M Go 中读取数据
- python - Python 正则表达式 - 查找不同行上两个特定单词之间的所有单词
- python - python类属性作为实例构造函数默认参数
- typescript - 空 | 数字不可分配给数字(即使在确保它不可能为空之后)
- nginx - 如何使用 Apache2/IP 地址公开 Svelte 应用程序?
- electron - 使用管理员权限运行电子应用程序(sudo yarn start)