我希望实现如下所示的内容。有一个 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())
正如您所见,foo
是 infoo
对象的容器。您可能在宇宙中单独拥有一个 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/