不同 return 类型,重载 __add__
Different return types, overloading __add__
我希望实现如下内容。有一个 class 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
的接口在有多个 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 惯例是 class 命名驼峰式和几乎所有其他名称 snake_case。
我希望实现如下内容。有一个 class 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
的接口在有多个 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 惯例是 class 命名驼峰式和几乎所有其他名称 snake_case。