如何修复__iter__方法

时间:2016-10-23 22:23:43

标签: python

from collections import defaultdict
from goody import type_as_str

class Bag:
    def __init__(self, i=None):
        self.bag = []
        if i == None:
            pass  # i is None, do nothing after create empty bag
        elif type(i)==list:
            self.bag.extend(i) # append whole list i into bag with extend method
        else:
            self.bag.append(i) # append single item i into bag 

    def __repr__(self):
        for s in self.bag :
            return s

    def __str__(self):
        for s in self.bag :
            return s

    def __len__ (self):
        if 'Bag()' in self.bag:
            return 0
        else:
            return len(self.bag)
    def unique(self):
        l = []
        if len(self.bag) == 0:
            return 0
        else:
            for x in self.bag:
                if x not in l:
                    l.append(x)
                else:
                    continue
            return len(l)

    def __contains__ (self,i):
        if i in self.bag:
            return True
        else:
            return False

    def count(self,i):
        return self.bag.count(i)

    def add(self,i):
        self.bag.append(i)

    def __add__(self,i):
        for x in i:
           self.bag.append(x)

    def remove(self,i):
        if i not in self.bag:
            raise ValueError
        for x in self.bag:
            if x == i:
                self.bag.remove(x)
                break


    def __eq__ (self,i):
        return self.bag == i 

    def __ne__ (self,i):
        return self.bag != i

    def __iter__(self):
        class PH_iter:
            def __init__(self,i):

                self.l = i

            def add(self,i):
                self.l.append(i)

            def remove(self,i):
                self.l.pop(i)

        return PH_iter(self.l)




if __name__ == '__main__':
#driver tests
import driver
driver.default_file_name = 'bsc1.txt'
#     driver.default_show_exception= True
#     driver.default_show_exception_message= True
#     driver.default_show_traceback= True
driver.driver()

Bag函数通常会返回一个列表。 Writing Bag()构造一个空袋子。书写袋([' d',' a'' b',' d'' c',& #39; b'' d'])制作一个包含一个'一个',一个''# 39;和三个。

iter 方法应该在bag类中定义,以便从列表中添加或删除项目。

输入是:

# Test iterator
e-->[i for i in sorted(b)]-->['a', 'b', 'b', 'c', 'd', 'd', 'd']
c-->i = iter(b)
c-->b.add('d')
c-->b.remove('a')
e-->[i for i in sorted(b)]-->['b', 'b', 'c', 'd', 'd', 'd', 'd']
e-->[i for i in sorted(x for x in i)]-->['a', 'b', 'b', 'c', 'd', 'd', 'd']

我得到的错误是:

 94 # Test iterator
 95 *Error: [i for i in sorted(b)] raised exception AttributeError: 'Bag' object has no attribute 'l'
 96 *Error: i = iter(b) raised exception AttributeError: 'Bag' object has no attribute 'l'
 99 *Error: [i for i in sorted(b)] raised exception AttributeError: 'Bag' object has no attribute 'l'
 100 *Error: [i for i in sorted(x for x in i)] raised exception NameError: name 'i' is not defined

任何人都可以帮我修复 iter 功能以使其正常工作吗?非常感谢。

1 个答案:

答案 0 :(得分:0)

__iter__中,此行导致运行时错误

return PH_iter(self.l)

应该是

return PH_iter(self.bag)

这个实现会在迭代后给你一些惊喜,因为它实际上修改了self.bag的数据内容

您可以通过

进行改进
def __iter__(self):
    class PH_iter:
        def __init__(self,i):
            self.l = list(i)  # make a copy of the list i