如何继承不同类型的对象

2024-10-03 13:26:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道发生这种异常是因为我试图继承多个内置类型,这些类型在C级别上无法相互协作

但是,如果我定义了一个非强制性字段运算符,我怎么能绕过它呢


class NonMandatoryField(str):
    def __new__(cls, field: str):
        if len(field) == 0:
            raise ValueError('mandatory field not satisfied')
        return super().__new__(cls, field)

和IntField验证程序:

class IntField(int):
    def __new__(cls, field: int):
        if type(field) != int:
            raise ValueError('int value not supplied')
        return super().__new__(cls, field)

我如何实施:

class NonMandatoryIntField(NonMandatoryField, IntField):
     pass


Tags: 类型fieldnewreturnifdefnotclass