我希望能够运行这个函数,而不需要在末尾添加.elements。例如,如果是seta=MySet([1,2,3])和setb=MySet([1,10,11]),我可以运行setc=seta.intersection(setb.elements),但不能没有.elements。我如何在不需要输入.elements的情况下运行它?
class MySet:
def __init__(self, elements):
self.elements=elements
def intersection(self, other_set):
self.other_set=other_set
new_set = []
for j in other_set:
if j in self.elements:
new_set.append(j)
new_set.sort()
return new_set 发布于 2018-10-04 11:26:23
很容易,您所要做的就是访问函数中的.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 发布于 2018-10-04 11:28:12
Make your set an iterable by defining __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实例上的迭代将无缝地迭代它包含的元素。
我强烈建议使用the collections.abc module;很明显,您正在尝试构建一个set-like对象,使用collections.abc.Set (或collections.abc.MutableSet)作为基类可以最容易地实现基本行为。
https://stackoverflow.com/questions/52638500
复制相似问题