Custom Search

Friday, January 21, 2011

python django defining __getitem__ on a class

python django defining __getitem__ on a class

# defining __getitem__ on a class make it iterable in python?
# cb[0] is the same as cb.__getitem__(0)

#############################################1

class Test3:

Data = {'name':'saju', 'sex':'male'}

def __init__(self):
print "----in----__init__----"

def __getitem__(self, item1):
return self.Data[item1]


t3 = Test3()
print t3['name']
print t3['sex']


# OUTPUT
# ======
# ----in----__init__----
# saju
# male

#############################################2

class Test1:

def __init__(self):
print "----in----__init__----"

def __getitem__(self, item1):
print "-----in-----__getitem__-----", item1
if item1==5:
raise Exception('End')#For stop iteration (otherwise it will go to a loop)


t1 = Test1()

print "=============="

t1['saju'] #<----------IMP
t1.__getitem__('saju')

print "=============="
for x in t1:
pass

# OUTPUT
# ======
# ----in----__init__----
# ==============
# -----in-----__getitem__----- saju
# -----in-----__getitem__----- saju
# ==============
# -----in-----__getitem__----- 0
# -----in-----__getitem__----- 1
# -----in-----__getitem__----- 2
# -----in-----__getitem__----- 3
# -----in-----__getitem__----- 4
# -----in-----__getitem__----- 5
# Traceback (most recent call last):
# File "getitem.py", line 26, in
# for x in t1:
# File "getitem.py", line 15, in __getitem__
# raise Exception('End')#For stop iteration (otherwise it will go to a loop)
# Exception: End


#############################################3

class Test2:

def __init__(self):
print "----in----__init__----"

def __getitem__(self, item1, item2=0):
print "-----in-----__getitem__-----", item1, item2
if item1==5:
raise Exception('End')#For stop iteration (otherwise it will go to a loop)


t2 = Test2()

print "=============="

t2['saju'] #<----------IMP
t2.__getitem__('saju','1000')

print "=============="

for x in t2:
pass

# OUTPUT
# ======
# ----in----__init__----
# ==============
# -----in-----__getitem__----- saju 0
# -----in-----__getitem__----- saju 1000
# ==============
# -----in-----__getitem__----- 0 0
# -----in-----__getitem__----- 1 0
# -----in-----__getitem__----- 2 0
# -----in-----__getitem__----- 3 0
# -----in-----__getitem__----- 4 0
# -----in-----__getitem__----- 5 0
# Traceback (most recent call last):
# File "getitem.py", line 72, in
# for x in t2:
# File "getitem.py", line 60, in __getitem__
# raise Exception('End')#For stop iteration (otherwise it will go to a loop)
# Exception: End



#############################################

No comments:

Post a Comment