首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python,重载魔术方法,同一魔术方法的多次使用

Python,重载魔术方法,同一魔术方法的多次使用
EN

Stack Overflow用户
提问于 2022-11-25 00:26:01
回答 1查看 28关注 0票数 0

是否有可能重载魔术方法或获得类似的结果,例如,C#中的重载方法对于python中的魔术方法?或者,这仅仅是这门语言的另一个障碍,在这个时刻,它不可能像过去的“类型”那样;)

代码语言:javascript
复制
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)

我试过试一试.

代码语言:javascript
复制
vector_one = Vector(1, 2, 3)
vector_two = Vector(4, 5, 6)

print(vector_one + vector_two)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-25 00:40:34

不,不可能自动过载,但您可以检查类型并相应地进行:

代码语言:javascript
复制
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 else
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74567336

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档