python type instance_Python type, types and isinstance()使用
#-*- coding:utf-8 -*-
'''
Created on 2011-12-11
作者: 李昱彤
Email: liqi1031@gmail.com
'''
def foo(data):
if type(data) == type(0):
print "你輸入了一個整數(shù)"
elif type(data) == type(''):
print "你輸入了一個字符串"
else:
print "只能輸入整數(shù)或字符串"
import types
def updateFoo(data):
if type(data) == types.IntType:
print "你輸入了一個整數(shù)"
elif type(data) == types.StringType:
print "你輸入了一個字符串"
else:
print "只能輸入整數(shù)或字符串"
def update2Foo(data):
if type(data) is types.IntType:
print "你輸入了一個整數(shù)"
elif type(data) is types.StringType:
print "你輸入了一個字符串"
else:
print "只能輸入整數(shù)或字符串"
def update3Foo(data):
if isinstance(data, (int)):
print "你輸入了一個整數(shù)"
elif isinstance(data, (str)):
print "你輸入了一個字符串"
else:
print "只能輸入整數(shù)或字符串"
def update4Foo(data):
if isinstance(data, (int)):
print "你輸入了一個整數(shù)"
elif isinstance(data, (str)):
print "你輸入了一個字符串"
else:
print "只能輸入整數(shù)或字符串"
update4Foo(1)
update4Foo("liyutong")
update4Foo([1,2])
運行結(jié)果:
你輸入了一個整數(shù)
你輸入了一個字符串
只能輸入整數(shù)或字符串
結(jié)論:建議使用isinstance() 去做相同的事情.
總結(jié)
以上是生活随笔為你收集整理的python type instance_Python type, types and isinstance()使用的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sketch 将动图转换为json_开源
- 下一篇: 先学python还是先学数据库_跟着销售