Reputation: 11
Tried to execute the below program along with values its printing None
. Can anyone help me why its printing 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()
Upvotes: 1
Views: 61
Reputation: 1121924
You need to raise the StopIteration
execption:
def __next__(self):
if self._roles:
return self._roles.pop()
else:
raise StopIteration
Because you don't raise
it, you are merely referencing the name, which does nothing. Then the __next__
method just ends, resulting in a default implicit return None
.
Upvotes: 1
Reputation: 42758
You should raise StopIteration
:
def __next__(self):
if self._roles:
return self._roles.pop()
else:
raise StopIteration
Upvotes: 1