Computer Science Canada

[Python-tut] Iterating Over any Object

Author:  wtd [ Thu Jul 14, 2005 4:39 am ]
Post subject:  [Python-tut] Iterating Over any Object

So we've seen how we can do this in Ruby. It's pretty darn simple.

code:
class Name
   attr_reader :first, :last

   def initialize(first, last)
      @first, @last = first, last
   end
 
   def each
      yield @first
      yield @last
   end
end


Well, as it turns out, it's pretty easy in Python too.

code:
class Name(object):
   def __init__(self, first, last):
      self.__first, self.__last = first, last
   first = property(lambda self: self.first)
   last  = property(lambda self: self.last)
   def __iter__(self):
      yield self.__first
      yield self.__last


We can now create a new Name object.

code:
bob = Name("Bob", "Smith")


And iterate over its component names.

code:
for name in bob:
   print name

Author:  MysticVegeta [ Fri Jul 29, 2005 7:44 am ]
Post subject: 

Isnt iteration calling of a same procedure inside that procedure in turing?
code:
proc something (x : int, y : int)
if y = 1 then
return
else
something(x, y-1)
end if
end something


Is that what you are talking about?

Author:  Mazer [ Fri Jul 29, 2005 8:47 am ]
Post subject: 

That's recrusion, MysticVegeta.

Author:  MysticVegeta [ Fri Jul 29, 2005 9:10 pm ]
Post subject: 

But the turing book says calling a procedure in that procedure is called iteration and calling a function inside the same function is called recursion... Confused

Author:  1of42 [ Fri Jul 29, 2005 9:36 pm ]
Post subject: 

If it says that, it's wrong.

Author:  Hikaru79 [ Fri Jul 29, 2005 9:48 pm ]
Post subject: 

MysticVegeta wrote:
But the turing book says calling a procedure in that procedure is called iteration and calling a function inside the same function is called recursion... Confused

Iteration is going through a set or list or array, etc, or objects/values/etc, in a sequential manner. Now, what the book might have given is a recursive example of iteration, which is entirely possible. However, there is a distinction between the two.


: