代码之家  ›  专栏  ›  技术社区  ›  Grismar

“int”子类的“__new__”方法中出现意外类型警告

  •  2
  • Grismar  · 技术社区  · 2 年前

    以下代码:

    class Foo(int):
        def __new__(cls, x, *args, **kwargs):
            x = x if isinstance(x, int) else 42
            
            return super(Foo, cls).__new__(cls, x, *args, **kwargs)
    

    导致警告(在PyCharm中):“ Expected type 'str | bytes | bytearray', got 'int' instead “在 x 在最后一行。

    为什么会这样?

    如果我评估 super(Size, cls).__new__ == int.__new__ ,结果是 True 。这难道不期待一个 int

    有没有更好的方法来创建的子类 int ,如果我想在第一次分配值或将某个值强制转换为此类型时添加行为?

    这样一个类的具体例子是 class Size(int) 可以实例化为 Size(1024) Size('1 KiB') ,结果相同。

    1 回复  |  直到 2 年前
        1
  •  2
  •   flakes    2 年前

    的过载 int 具有多个参数时,将一个字符串作为第一个参数。大致相当于

    int(x:int = 0) -> int:
    int(x:str, base: int = 10) -> int:
    

    您正在提供 __new__(cls, x, *args, **kwargs) ,因此期望应该有一个字符串作为第一个参数。

    因此,为了不抱怨,请去掉额外的args:

    class Foo(int):
        def __new__(cls, x):
            x = x if isinstance(x, int) else 42
            return super(Foo, cls).__new__(cls, x)
    
    
    print(Foo(2))
    print(Foo("2"))
    
    2
    42