是否有可能重载魔术方法或获得类似的结果,例如,C#中的重载方法对于python中的魔术方法?或者,这仅仅是这门语言的另一个障碍,在这个时刻,它不可能像过去的“类型”那样;)
def __init__(self, x:float, y:float, z:float) -> None:
self.x = x
self.y = y
self.z = z
def __add__(self, other:'Vector') -> 'Vector':
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
def __add__(self, other:float) -> 'Vector':
return Vector(self.x + other, self.y + other, self.z + other)我试过试一试.
vector_one = Vector(1, 2, 3)
vector_two = Vector(4, 5, 6)
print(vector_one + vector_two)

发布于 2022-11-25 00:40:34
不,不可能自动过载,但您可以检查类型并相应地进行:
from typing import Union
class Vector:
# ...
def __add__(self, other: Union['Vector', float]) -> 'Vector':
if type(other) == Vector:
return Vector(self.x + other.x, self.y + other.y, self.z + other.z)
elif type(other) == float:
return Vector(self.x + other, self.y + other, self.z + other)
else:
raise TypeError # or something elsehttps://stackoverflow.com/questions/74567336
复制相似问题