我想有一个自定义的元类,looks like的定义是TypedDict.

当你声明一个新的TypedDict,我们写这样的东西:

from typing import TypedDict

class MyClass(TypedDict, total=False):
  pass

但是,当我声明一个元类时,它看起来像这样:

class MetaSerial(type):
  def __new__(pls, name, bases, act, exclude: list[str] = [], custom: list[str] = []):
    dct["_exclude"] = exclude
    dct["_custom"] = custom
    return super().__new__(cls, name, bases, dct)

class Serial(metaclass=MetaSerial, exclude=["value"], custom=["terminals"]):
  pass

所以,百万美元的问题是:有没有一种方法让我摆脱恼人的metaclass=,并使用类似的东西:

class Serial(MetaSerial, exclude=["value"], custom=["terminals"]):
  pass

推荐答案

尽可能避免元类(您定义的每个元类都可能与另一个元类发生冲突).这里所需要的只是一个带有适当的__init_subclass__方法的基类.

class SerialBase:
    def __init_subclass__(cls, exclude: list[str] = None, custom: list[str] = None, **kwargs):
        super().__init_subclass__(**kwargs)
        if exclude is None:
            exclude = []

        if custom is None:
            custom = []

        cls._exclude = exclude
        cls._custom = custom

class Serial(SerialBase, exclude=["value"], custom=["terminals"]):
    pass

Python相关问答推荐

由于NEP 50,向uint 8添加-256的代码是否会在numpy 2中失败?

使用miniconda创建环境的问题

对于一个给定的数字,找出一个整数的最小和最大可能的和

什么相当于pytorch中的numpy累积ufunc

从dict的列中分钟

计算组中唯一值的数量

如何将Docker内部运行的mariadb与主机上Docker外部运行的Python脚本连接起来

如果条件不满足,我如何获得掩码的第一个索引并获得None?

NumPy中条件嵌套for循环的向量化

如何在Python中找到线性依赖mod 2

Python逻辑操作作为Pandas中的条件

在matplotlib中删除子图之间的间隙_mosaic

Pandas—堆栈多索引头,但不包括第一列

如何在Airflow执行日期中保留日期并将时间转换为00:00

我什么时候应该使用帆布和标签?

为什么dict. items()可以快速查找?

类型对象';敌人';没有属性';损害';

FileNotFoundError:[WinError 2]系统找不到指定的文件:在os.listdir中查找扩展名

对包含JSON列的DataFrame进行分组

对当前的鼹鼠进行编码,并且我的按键获得了注册