为什么 Python NewType 与 isinstance 和 type 不兼容?

rag*_*ojp 7 python-typing

这似乎不起作用:

from typing import NewType

MyStr = NewType("MyStr", str)
x = MyStr("Hello World")

isinstance(x, MyStr)
Run Code Online (Sandbox Code Playgroud)

我什至不明白False,但TypeError: isinstance() arg 2 must be a type or tuple of types因为MyStr是一个函数并且isinstance需要一个或多个type

甚至assert type(x) == MyStr失败is MyStr

我究竟做错了什么?

Son*_*ARG 0

交叉引用: 从 str 或 int 继承

在同一问题中更详细: /sf/answers/187166171/


如果您想子类化 Python 的str,您需要执行以下操作:

class MyStr(str):
  # Class instances construction in Python follows this two-step call:
  # First __new__, which allocates the immutable structure,
  # Then __init__, to set up the mutable part.
  # Since str in python is immutable, it has no __init__ method.
  # All data for str must be set at __new__ execution, so instead
  # of overriding __init__, we override __new__:
  def __new__(cls, *args, **kwargs):
    return str.__new__(cls, *args, **kwargs)
Run Code Online (Sandbox Code Playgroud)

然后:

x = MyStr("Hello World")

isinstance(x, MyStr)
Run Code Online (Sandbox Code Playgroud)

True按预期返回

  • `MyStr` 不应是 `str`,而是不同的类型,因此我使用了 `NewType`。 (2认同)