使用__repr__ Python

时间:2018-10-04 03:22:52

标签: python python-3.x

我希望能够运行此功能而无需在末尾添加.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 

2 个答案:

答案 0 :(得分:1)

您只需要做的就是访问函数中的.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 

答案 1 :(得分:1)

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的对象,并且通过使用collections.abc.Set(或collections.abc.MutableSet)作为基类来最简单地实现基本行为。