Python-Ref > Object oriented programming > Basics > Emulating iterable types
 
 

<-^^->

Emulating iterable types

How to provide the ability to iterate over your custom objects.
Expand/Shrink
Zdroj: (oop-emul1-1.py)
  1   import urllib2
  2   import re
  3   
  4   class Links( object):
  5     """provides an iterator over links from a HTML page"""
  6   
  7     def __init__( self, text=""):
  8       self.text = ""
  9       self._index = 0
 10   
 11     def read_url( self, url):
 12       try:
 13         f = urllib2.urlopen( url)
 14       except urllib2.URLError:
 15         return False
 16       self.text = f.read()
 17       f.close()
 18       return True
 19   
 20     def __iter__( self):
 21       return self
 22   
 23     def next( self):
 24       """next step of the iterator"""
 25       regexp = re.compile( '<a\s+href="(.*?)".*?>', re.S|re.I)
 26       m = regexp.search( self.text, pos=self._index)
 27       if m:
 28         self._index = m.end( 1)  end position of the match
 29         return m.group( 1)
 30       else:
 31         raise StopIteration
 32   
 33   l = Links()
 34   l.read_url( "http://google.com")
 35   for link in l:
 36     print link
stdout:
http://images.google.cz/imghp?hl=cs&tab=wi
http://news.google.cz/nwshp?hl=cs&tab=wn
http://groups.google.cz/grphp?hl=cs&tab=wg
http://picasaweb.google.cz/home?hl=cs&tab=wq
http://mail.google.com/mail/?hl=cs&tab=wm
http://www.google.cz/intl/cs/options/
http://docs.google.com/?hl=cs&tab=wo
http://www.google.cz/reader/view/?hl=cs&tab=wy
http://www.google.cz/intl/cs/options/
/url?sa=p&pref=ig&pval=3&q=http://www.google.cz/ig%3Fhl%3Dcs%26source%3Diglk&usg=AFQjCNEjIy3HcIoHHp-ysNPPMy6WitPxSg
https://www.google.com/accounts/Login?continue=http://www.google.cz/&hl=cs
/intl/cs/ads/
/intl/cs/about.html
Doba běhu: 741.1 ms