为什么这段代码打印无?

时间:2016-08-05 06:50:31

标签: python

尝试执行以下程序及其打印None的值。任何人都可以帮我解释打印None的原因吗?

class Myself(object):
    def __init__(self):
        self.record={}
    def __iter__(self):
        self._roles = list(self.record.keys())
        #print ("in iter self._roles",type(self._roles))
        return self
    def __next__(self):
        if self._roles:
            return self._roles.pop()
        else:
            StopIteration

    def __setitem__(self,key,value):
        self.record[key]=value
    def __getitem__(self,key):
        return self.record.get(key,"No record found")

    def list_all(self):
        for detail in self.record:
            print (self.record[detail])

def main():
    mydetails = Myself()

    mydetails['name']='Python'
    mydetails['age']='26'
    mydetails['job']='software'
    mydetails.list_all()

    for x in mydetails:
        print (x,":",mydetails[x])

main()

2 个答案:

答案 0 :(得分:1)

你应该举起StopIteration

def __next__(self):
    if self._roles:
        return self._roles.pop()
    else:
        raise StopIteration

答案 1 :(得分:1)

您需要提升 StopIteration execption:

def __next__(self):
    if self._roles:
        return self._roles.pop()
    else:
        raise StopIteration

因为你没有raise它,所以你只是引用了名称,它什么都不做。然后__next__方法结束,导致默认隐式return None