2 回答

TA贡献1862条经验 获得超7个赞
通过定义使您的集合成为可迭代的__iter__:
class MySet:
def __init__(self, elements):
self.elements=elements
def intersection(self, other_set):
...
def __iter__(self):
return iter(self.elements)
# Or for implementation hiding, so the iterator type of elements
# isn't exposed:
# yield from self.elements
现在迭代MySet无缝地迭代它包含的元素。
我强烈建议看的collections.abc模块; 您显然正在尝试构建一个类似set对象,并且使用collections.abc.Set(or collections.abc.MutableSet) 作为基类最容易使基本行为到位。

TA贡献1858条经验 获得超8个赞
很容易,您所要做的就是访问.elements函数中的 。不需要__repr__。
class MySet:
def __init__(self, elements):
self.elements=elements
def intersection(self, setb):
other_set = setb.elements
new_set = []
for j in other_set:
if j in self.elements:
new_set.append(j)
new_set.sort()
return new_set
添加回答
举报