为了账号安全,请及时绑定邮箱和手机立即绑定

使用 __repr__ Python

使用 __repr__ Python

长风秋雁 2021-06-28 12:39:58
我希望能够运行此功能而无需添加.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 回答

?
牧羊人nacy

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) 作为基类最容易使基本行为到位。


查看完整回答
反对 回复 2021-07-06
?
猛跑小猪

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 


查看完整回答
反对 回复 2021-07-06
  • 2 回答
  • 0 关注
  • 248 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号