{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Iteratorların Oluşturulması ve Kullanılması\n", "\n", "Bu konuda iteratorları oluşturmayı, kullanmayı ve kendi objelerimizi **iterable** (üzerinde gezinilebilecek) olarak nasıl yazarız öğrenmeye çalışacağız. İlk olarak iteratorlar nedir anlamaya çalışalım\n", "\n", "### Iteratorlar nedir? \n", "\n", "Iteratorlar aslında Pythonda çoğu yerde biz görmesek de kullanılır. Iteratorlar özellikle for döngülerinde , list comprehensionlarında, ve bir sonraki derste göreceğimiz generatorlarda karşımıza çıkar.\n", "\n", "Iteratorlar en genel anlamıyla üzerinde gezinilebilecek bir **objedir** ve bu obje her seferinde bir tane eleman döner.\n", "\n", "Pythonda kendisinden iterator oluşturabileceğimiz her **obje iterable bir objedir.**. Örneğin, demetlerden,listelerden ve stringlerden oluşturduğumuz bütün objeler **iterable** bir objedir. \n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Bir objenin **iterable** olması için hazır metodlar olan \\__iter()\\__ ve \\__next()\\__ metodlarını mutlaka tanımlaması gerekir." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Iterator oluşturma\n", "\n", "Bir iterator objesini , **iterable** bir objeden (liste,demet,string vs) oluşturmak için Pythonda ***iter()*** fonksiyonunu kullanıyoruz ve bu objenin bir sonraki elemanını almak için ***next()*** fonksiyonu kullanıyoruz." ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "collapsed": true }, "outputs": [], "source": [ "liste = [1,2,3,4,5]" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['__add__',\n", " '__class__',\n", " '__contains__',\n", " '__delattr__',\n", " '__delitem__',\n", " '__dir__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getitem__',\n", " '__gt__',\n", " '__hash__',\n", " '__iadd__',\n", " '__imul__',\n", " '__init__',\n", " '__init_subclass__',\n", " '__iter__',\n", " '__le__',\n", " '__len__',\n", " '__lt__',\n", " '__mul__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__reversed__',\n", " '__rmul__',\n", " '__setattr__',\n", " '__setitem__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " 'append',\n", " 'clear',\n", " 'copy',\n", " 'count',\n", " 'extend',\n", " 'index',\n", " 'insert',\n", " 'pop',\n", " 'remove',\n", " 'reverse',\n", " 'sort']" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "dir(liste) # __iter__ metodu tanımlı olduğu için listeler üzerinde iterator oluşturabiliriz." ] }, { "cell_type": "code", "execution_count": 68, "metadata": { "collapsed": true }, "outputs": [], "source": [ "iterator = iter(liste) # Iterator oluşturma" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(iterator) # next metoduyla sıradaki eleman" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(iterator) # next metoduyla sıradaki eleman" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(iterator) # next metoduyla sıradaki eleman" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 72, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(iterator)" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 73, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(iterator)" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "ename": "StopIteration", "evalue": "", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mStopIteration\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mnext\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0miterator\u001b[0m\u001b[1;33m)\u001b[0m \u001b[1;31m# Eleman kalmadığı için \"StopIteration\" hatası\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mStopIteration\u001b[0m: " ] } ], "source": [ "next(iterator) # Eleman kalmadığı için \"StopIteration\" hatası" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "İşte **iterable** bir objeden bir iterator'ı bu şekilde oluşturup, ***next()*** fonksiyonuyla objenin sıradaki elemanını alabiliyoruz. Ancak eleman kalmayınca **StopIteration** hatasını alıyoruz. İşte **iteratorların** kullanımı bu şekildedir. Aslında biz farketmesek de Pythondaki **for döngüleri** aslında bir objenin üzerinde gezinirken **iteratorları** kullanır. " ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n" ] } ], "source": [ "liste = [1,2,3,4,5]\n", "\n", "for i in liste:\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Aslında **for döngülerinin** iç yapısı şu şekildedir;\n" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n" ] } ], "source": [ "liste = [1,2,3,4,5]\n", "\n", "iterator = iter(liste)\n", "\n", "while True:\n", " try:\n", " print(next(iterator))\n", " \n", " except StopIteration:\n", " break\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Kendi Iterable Objelerimizi Oluşturmak\n", "Peki biz kendi oluşturduğumuz veritiplerini nasıl **iterable** yapacağız ? Bunun için oluşturacağımız sınıfların **mutlaka** \\__iter()\\__ ve \\__next()\\__ metodlarını tanımlaması gereklidir. Şimdi bir tane kumanda sınıfı oluşturalım ve bu sınıfı **iterable** yapalım." ] }, { "cell_type": "code", "execution_count": 78, "metadata": { "collapsed": true }, "outputs": [], "source": [ "class Kumanda():\n", " def __init__(self,kanal_listesi):\n", " self.kanal_listesi = kanal_listesi # Kanal Listemiz\n", " self.index = -1 # İndeksimiz\n", " \n", " def __iter__(self):\n", " return self # iterator oluşturduğumuzda (iter fonksiyonu çağrıldığında )objemizi döneceğiz.\n", " def __next__(self): # next fonksiyonu çağrıldığında burası çalışacak.\n", " self.index += 1\n", " if (self.index < len(self.kanal_listesi)):\n", " return self.kanal_listesi[self.index]\n", " else:\n", " self.index = -1\n", " raise StopIteration" ] }, { "cell_type": "code", "execution_count": 80, "metadata": { "collapsed": true }, "outputs": [], "source": [ "kumanda = Kumanda([\"Kanal d\",\"Trt\",\"Atv\",\"Fox\",\"Bloomberg\"]) # Objemizi oluşturuyoruz." ] }, { "cell_type": "code", "execution_count": 81, "metadata": { "collapsed": true }, "outputs": [], "source": [ "iterator = iter(kumanda) # Objemiz iterable olduğu için iterator oluşturulabilir." ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Kanal d'" ] }, "execution_count": 82, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(iterator)" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Trt'" ] }, "execution_count": 83, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(iterator)" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Atv'" ] }, "execution_count": 84, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(iterator)" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Fox'" ] }, "execution_count": 85, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(iterator)" ] }, { "cell_type": "code", "execution_count": 86, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Bloomberg'" ] }, "execution_count": 86, "metadata": {}, "output_type": "execute_result" } ], "source": [ "next(iterator)" ] }, { "cell_type": "code", "execution_count": 87, "metadata": {}, "outputs": [ { "ename": "StopIteration", "evalue": "", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mStopIteration\u001b[0m Traceback (most recent call last)", "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mnext\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0miterator\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;32m\u001b[0m in \u001b[0;36m__next__\u001b[1;34m(self)\u001b[0m\n\u001b[0;32m 12\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 13\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mindex\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m-\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 14\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mStopIteration\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[1;31mStopIteration\u001b[0m: " ] } ], "source": [ "next(iterator)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Güzel ! Objemizi **iterable** yapmayı başardık. Objemiz **iterable** olduğuna göre artık **for** döngüsüyle üzerinde gezinebiliriz." ] }, { "cell_type": "code", "execution_count": 88, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Kanal d\n", "Trt\n", "Atv\n", "Fox\n", "Bloomberg\n" ] } ], "source": [ "for i in kumanda:\n", " print(i)" ] }, { "cell_type": "code", "execution_count": 89, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Kanal d\n", "Trt\n", "Atv\n", "Fox\n", "Bloomberg\n" ] } ], "source": [ "for i in kumanda:\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "İşte Pythonda iteratorların kullanımı bu şekilde ! Artık iterator kullanmayı ve kendi objelerimizi **iterable** yapmayı biliyoruz." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.1" } }, "nbformat": 4, "nbformat_minor": 2 }