你能改变按位或自定义类型的行为吗



由于Python 3.10,您可以使用type1 | type2而不是Union[type1, type2]来注释类型,例如:int | float

你能改变按位或自定义类型的行为吗?即,如果我创建自己的类型:

class A(type):
pass

我想自定义A | int的结果,比如:

class A(type):
__class_or__(cls, other) -> 'MyOwnCustomUnion': ...

这可能吗?

我试着在元类上定义__or__(self, other): ...,但没有任何作用:

class A(type):
def __or__(self, other):
print(other)
return super(A, self).__or__(other)

print(A | int)
# prints "__main__.A | int", does not print "<class 'int'>" as expected.

正如@jonrrier在评论中指出的那样,它必须实现"高于A"一级;,(对不起,我不知道该怎么更好地表达。

这项工作:

class MyUnion:
def __init__(self, a, b):
self.a = a
self.b = b

class A(type):
def __or__(self, other) -> MyUnion:
return MyUnion(self, other)

class B(type, metaclass=A):
pass

print(B | int)
# <__main__.MyUnion object at 0x000001824C7B3040>

最新更新