python - 返回类型不同,重载__add__

标签 python addition magic-methods

我希望实现如下所示的内容。有一个 foo 类,其中包含 infoo 对象的列表。我在想,为了重载 __add__ 运算符,我应该

class foo(object):
    def __init__(self, infoo_list):
        self.args = infoo_list

    def __add__(self, other):
        if isinstance(other, type(self)):
            newargs = self.args + other.args
            return foo(newargs)
        elif isinstance(other, infoo_type):
            newargs = self.args + [other]
            return foo(newargs)


class infoo (object):
    def __init__(self):
        pass

    def __add__(self, other):
        return foo([self, other])


infoo_type = type(infoo())

正如您所见,fooinfoo 对象的容器。您可能在宇宙中单独拥有一个 infoo 对象并对其进行操作。但是,无论如何,如果您必须管理多个对象,foo 对象就会发挥作用。

尽管用户可以实例化一个 infoo 对象来播放,但代码的目的是让 foo 的接口(interface)在有多个 infoo 时进行处理.

这是好的做法吗?我是否违反了一些黄金法则?

最佳答案

基本上已在评论中涵盖,但类似这样的设计将是一个更简洁的设计:

class InFoo:
    pass

class Foo:
    def __init__(self, infoos):
        self.args = list(infoos)

    def __add__(self, other):
        if isinstance(other, __class__):
            oargs = other.args
        elif isinstance(other, InFoo):
            oargs = [other]
        return foo(self.args + oargs)

似乎没有任何充分的理由在 InFoo 上定义 __add__,因为在这种情况下,添加仅对容器有意义。这也消除了外部定义 infoo_type 的需要。 Python 约定是使类名采用 CamelCase 命名,而其他几乎所有内容都采用 Snake_case。

关于python - 返回类型不同,重载__add__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66803769/

相关文章:

python - 值错误 : The computed initial MA coefficients are not invertible You should induce invertibility

python - 端点可以忽略 Flask 中的 'after request' 装饰器吗?

python - 在Pandas Dataframe中获取语法错误

python - 什么是用户控制的命名空间?

javascript - 如何删除 :hover from element when suddenly browser window lost focus?

python - 如何在 django modelForm 中向输入类型 'multiple' 添加 ='file' 属性?

ajax - 提交时使用 ajax 将子表单添加到表单

汇编、栈上局部变量的算术运算

javascript - jQuery:更改输入值不用于新添加

php - Yii 和 PHP 初始化与构造问题