在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Python/ Python在做條件比較的時(shí)候如何讓其左右類型不同的時(shí)候報(bào)錯(cuò)或提示?

Python在做條件比較的時(shí)候如何讓其左右類型不同的時(shí)候報(bào)錯(cuò)或提示?

例如

mstr = '1'
mint = 1
if mstr == mint:
    print 'same'

可是這樣是沒有意義的,我想要的是

mstr = '1'
mint = 1
if int(mstr) == mint:
    print 'same'

但是我事先并不知道m(xù)str是一個(gè)字符串,如何在不做實(shí)現(xiàn)類型判斷的條件下,比較的時(shí)候報(bào)錯(cuò)或者提示呢?

回答
編輯回答
朽鹿
if int(mstr) == mint:
    print 'same'

你自己已經(jīng)寫出來了啊, mstr不知道類型是什么,如果不能轉(zhuǎn)換成int,會(huì)報(bào)ValueError,如果不想報(bào)異常

try:
    if int(mstr) == mint:
        print 'same'
except ValueError:
    print mstr

還是你的意思是想先判斷類型?

if type(mstr) == type(mint):
    if mstr == mint:
        print 'same'
    else:
        print 'value not same'
else:
    print 'type not same'

還是你既不想先判斷類型,還想報(bào)錯(cuò),函數(shù)重載?

class myint(int):
    def __eq__(self, other):
        if isinstance(other, int):
            return int(self) == other
        else:
            print 'type not same'
            return False

mint = myint(1)
1 == mint
mstr == mint
2017年7月20日 21:28