猿问

使用 __repr__ Python

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


长风秋雁
浏览 249回答 2
2回答

牧羊人nacy

通过定义使您的集合成为可迭代的__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) 作为基类最容易使基本行为到位。

猛跑小猪

很容易,您所要做的就是访问.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 
随时随地看视频慕课网APP

相关分类

Python
我要回答