python技巧31[对象相等性|dictionary模拟switchcase]


一  对象相等性比较

python 对于string,tuple,list,dict,只要内容相等则为相等,但是对于自定义对象则不是。

 

print('---------------str-------------------------')

mystr
=""
mystr2
="test"
mystr3
='test'
if mystr == "" : print('str is empty')
if len(mystr) == 0 : print('str is empty')
if len(mystr2) : print('if not empty, print')

if mystr2 == "test" : print('the strs are equal')
if mystr2 == mystr3 : print('the strs are equal')
if mystr2 != 'aa' : print('the strs are not equal')

print('---------------list------------------------')

mylist
=[]
mylist2
=[1,2,3]
mylist3
=[1,2,3]
if mylist == [] : print('list is empty')
if len(mylist) == 0 : print('list is empty')
if len(mylist2) : print('if not empty, print')


if mylist2 == [1,2,3] : print('the lists are equal')
if mylist2 == mylist3 : print('the lists are equal')
if mylist != [1,2] : print('the lists are not equal')

print('---------------set/dictionary--------------')
myset
={'one','two'}
if myset == {"one",'two'} : print('two sets are equal')

mydict
={'one':1'two':2}
mydict2
={'one':1'two':2}
if mydict == mydict2 : print('two dicts are equal')

print('---------------object----------------------')

class MyClass :
    
def __init__(self,x,y):
        self.x 
= x
        self.y 
= y

if MyClass(1,2!= MyClass(1,2) : print('the two objects are not equal')

print('---------------end------------------------')

 

结果:

---------------str-------------------------
str is empty
str is empty
if not empty, print
the strs are equal
the strs are equal
the strs are not equal
---------------list------------------------
list is empty
list is empty
if not empty, print
the lists are equal
the lists are equal
the lists are not equal
---------------set/dictionary--------------
two sets are equal
two dicts are equal
---------------object----------------------
the two objects are not equal
---------------end------------------------ 


 二 dictionary来模拟switchcase
def key_1_pressed():
    
print ('Key 1 Pressed')

def key_2_pressed():
    
print ('Key 2 Pressed')

def key_3_pressed():
    
print ('Key 3 Pressed')

def unknown_key_pressed():
    
print ('Unknown Key Pressed')
    
keycode 
= 2
if keycode == 1:
   key_1_pressed()
elif keycode == 2:
   key_2_pressed()
elif number == 3:
   key_3_pressed()
else:
   unknown_key_pressed()


keycode2 
= 2
functions 
= {1: key_1_pressed, 2: key_2_pressed, 3: key_3_pressed}
functions.get(keycode2, unknown_key_pressed)()


完!

 

 


作者:iTech
微信公众号: cicdops
出处:http://itech.cnblogs.com/
github:https://github.com/cicdops/cicdops

posted @ 2009-12-14 17:20  iTech  阅读(1810)  评论(0编辑  收藏  举报