python類型檢查
Ⅰ python 中怎麼查看數據類型
有時候我們需要知道變數類型,但不知道如何查看
內置函數isinstance(object, (type1,type2...))
isinstance('content', str)
返回True or False
使用內置函數type(object)
在介紹數據類型的文章中提到過,要怎麼樣查看對像的數據類型。type()就是一個最實用又簡單的查看數據類型的方法。type()是一個內建的函數,調用它就能夠得到一個反回值,從而知道想要查詢的對像類型信息。
type使用方法
>>>type(1)
<type 'int'> #返回整形>>>type('content')
<type 'str'> #返回字元串
type返回值屬於type類型
>>>type(type(1))
<type 'type'> #返回type類型
Ⅱ python判斷數據類型有幾種方法,有啥優缺點
123456789
class A: passclass B(A): passa=A()b=B() print('a is an A:%s;b is an A:%s'%(isinstance(a,A),isinstance(b,A)))print('type of a is %s;type of b is %s'%(type(a),type(b)))
通常我們判斷是什麼類型,那麼只是想直到這個對象是否含有我們所需要的方法或者屬性,這樣在調用的時候就不會出錯,否則就要進行異常捕捉。而isinstance這個方法非常滿足這個需求。以上是示例代碼。
可以看出isinstance(a,A),isinstance(b,A)兩個返回的都是True,如果我們把a,b都當做A的實例使用完全沒問題,但是我們並不關心b是A的實例還是B的實例,因為他肯定包含A類定義中的所有屬性和方法,正常調用不會出現異常。
type的話出來的則是一串字元串,精確到子類,所以可以用來做精確判斷,例如判斷是不是這個類,而不是這個類的子類,isinstance只能判斷是不是這個類或者這個類的子類。
判斷兩個對象是否來自同一個類,可以用type(a)==type(b)來判斷。
Ⅲ python如何查看數據類型
python怎麼查看數據類型?
第一步我們首先需要知道在python中查看變數數據類型是使用type()函數,type函數的用法如下圖所示:
第二步我們打開py文件,輸入
import numpy as npa1=123list=[1,2,3,4,5,6]array=np.array(list)print(type(a1))
列印出a1變數的數據類型,如下圖所示:
第三步運行py文件之後,可以看到a1變數是int類型,如下圖所示:
第四步輸入
print(type(list))print(type(array))
列印出list變數和array變數的類型,如下圖所示:
第五步運行py文件,可以看到分別是列表和數組類型,如下圖所示:
以上就是python怎麼查看數據類型的詳細內容,更多請關注 腳本之家其它相關文章
Ⅳ python如何判斷輸入參數是int類型的
python判斷輸入參數是int類型的方法:
用if語句判斷「type(eval(輸入參數))」是否是int類型,python的eval函數可以去掉輸入參數的引號
示例代碼如下:
執行結果如下:
更多Python知識,請關註:Python自學網!!
Ⅳ Python中為什麼推薦使用isinstance來進行類型判斷
type比較的結果a和b的類型是一樣的,結果明顯是不準確的。這種古典類的實例,type返回的結果都是一樣的,而這樣的結果不是我們想要的。對於內建的基本類型來說,使用tpye來檢查是沒有問題的,可是當應用到其他場合的時候,type就顯得不可靠了。這個時候我們就需要使用isinstance來進行類型檢查。
Ⅵ python 怎麼查看數據類型
調試的時候可以看到,自己賦值的時候也可以
Ⅶ python 怎麼判斷list里元素類型
可以通過tpye()方法來判斷list里的元素類型。代碼舉例如下:
testList = [1, 2, 'a', [1, 2]]
for listElement in testList:
print '%s 的類型是:%s' % (listElement, type(listElement))
其中,for in語句用來遍歷testList這個list里的元素,然後分別列印出元素對應的類型,運行程序,輸出結果為:
1 的類型是:<type 'int'>
2 的類型是:<type 'int'>
a 的類型是:<type 'str'>
[1, 2] 的類型是:<type 'list'>
(7)python類型檢查擴展閱讀
python語言中type()函數介紹:
1、type()函數的作用
在python中type()是即簡單又實用的一種對象數據類型查詢方法。它是一個內建的函數,調用它就能夠得到一個反回值,從而知道想要查詢的對像類型信息。
2、type()函數使用方法:type(對象)
type()是接收一個對象當做參考,之後反回對象的相應類型。例如:
type(1)
<type 'int'> #整型
type("iplaypython")
<type 'str'> #字元串
Ⅷ python如何判斷類型
python中是可以判斷對象的類型的,判斷python中的對象類型,可以使用isinstance()函數。
isinstance是Python中的一個內建函數。是用來判斷一個對象的變數類型。函數語法格式為
isinstance(object, class-or-type-or-tuple)
如果參數object是classinfo的實例,或者object是classinfo類的子類的一個實例, 返回True。如果object不是一個給定類型的的對象, 則返回結果總是False。
例如
>>> isinstance(1, int)
True
>>> isinstance(1.0, float)
True
Ⅸ python3怎樣檢查網站構建的技術類型
示例函數
為了開發類型檢查器,我們需要一個簡單的函數對其進行實驗。歐幾里得演算法就是一個完美的例子:
def gcd(a, b):
'''Return the greatest common divisor of a and b.'''
a = abs(a)
b = abs(b)
if a < b:
a, b = b, a
while b != 0:
a, b = b, a % b
return a
在上面的示例中,參數 a 和 b 以及返回值應該是 int 類型的。預期的類型將會以函數註解的形式來表達,函數註解是 Python 3 的一個新特性。接下來,類型檢查機制將會以一個裝飾器的形式實現,註解版本的第一行代碼是:
def gcd(a: int, b: int) -> int:
使用「gcd.__annotations__」可以獲得一個包含註解的字典:
>>> gcd.__annotations__
{'return': <class 'int'>, 'b': <class 'int'>, 'a': <class 'int'>}
>>> gcd.__annotations__['a']
<class 'int'>
需要注意的是,返回值的註解存儲在鍵「return」下。這是有可能的,因為「return」是一個關鍵字,所以不能用作一個有效的參數名。
檢查返回值類型
返回值註解存儲在字典「__annotations__」中的「return」鍵下。我們將使用這個值來檢查返回值(假設註解存在)。我們將參數傳遞給原始函數,如果存在註解,我們將通過註解中的值來驗證其類型:
def typecheck(f):
def wrapper(*args, **kwargs):
result = f(*args, **kwargs)
return_type = f.__annotations__.get('return', None)
if return_type and not isinstance(result, return_type):
raise RuntimeError("{} should return {}".format(f.__name__, return_type.__name__))
return result
return wrapper
我們可以用「a」替換函數gcd的返回值來測試上面的代碼:
Traceback (most recent call last):
File "typechecker.py", line 9, in <mole>
gcd(1, 2)
File "typechecker.py", line 5, in wrapper
raise RuntimeError("{} should return {}".format(f.__name__, return_type.__name__))
RuntimeError: gcd should return int
由上面的結果可知,確實檢查了返回值的類型。
檢查參數類型
函數的參數存在於關聯代碼對象的「co_varnames」屬性中,在我們的例子中是「gcd.__code__.co_varnames」。元組包含了所有局部變數的名稱,並且該元組以參數開始,參數數量存儲在「co_nlocals」中。我們需要遍歷包括索引在內的所有變數,並從參數「args」中獲取參數值,最後對其進行類型檢查。
得到了下面的代碼:
def typecheck(f):
def wrapper(*args, **kwargs):
for i, arg in enumerate(args[:f.__code__.co_nlocals]):
name = f.__code__.co_varnames[i]
expected_type = f.__annotations__.get(name, None)
if expected_type and not isinstance(arg, expected_type):
raise RuntimeError("{} should be of type {}; {} specified".format(name, expected_type.__name__, type(arg).__name__))
result = f(*args, **kwargs)
return_type = f.__annotations__.get('return', None)
if return_type and not isinstance(result, return_type):
raise RuntimeError("{} should return {}".format(f.__name__, return_type.__name__))
return result
return wrapper
在上面的循環中,i是數組args中參數的以0起始的索引,arg是包含其值的字元串。可以利用「f.__code__.co_varnames[i]」讀取到參數的名稱。類型檢查代碼與返回值類型檢查完全一樣(包括錯誤消息的異常)。
為了對關鍵字參數進行類型檢查,我們需要遍歷參數kwargs。此時的類型檢查幾乎與第一個循環中相同:
for name, arg in kwargs.items():
expected_type = f.__annotations__.get(name, None)
if expected_type and not isinstance(arg, expected_type):
raise RuntimeError("{} should be of type {}; {} specified".format(name, expected_type.__name__, type(arg).__name__))
得到的裝飾器代碼如下:
def typecheck(f):
def wrapper(*args, **kwargs):
for i, arg in enumerate(args[:f.__code__.co_nlocals]):
name = f.__code__.co_varnames[i]
expected_type = f.__annotations__.get(name, None)
if expected_type and not isinstance(arg, expected_type):
raise RuntimeError("{} should be of type {}; {} specified".format(name, expected_type.__name__, type(arg).__name__))
for name, arg in kwargs.items():
expected_type = f.__annotations__.get(name, None)
if expected_type and not isinstance(arg, expected_type):
raise RuntimeError("{} should be of type {}; {} specified".format(name, expected_type.__name__, type(arg).__name__))
result = f(*args, **kwargs)
return_type = f.__annotations__.get('return', None)
if return_type and not isinstance(result, return_type):
raise RuntimeError("{} should return {}".format(f.__name__, return_type.__name__))
return result
return wrapper
將類型檢查代碼寫成一個函數將會使代碼更加清晰。為了簡化代碼,我們修改錯誤信息,而當返回值是無效的類型時,將會使用到這些錯誤信息。我們也可以利用 functools 模塊中的 wraps 方法,將包裝函數的一些屬性復制到 wrapper 中(這使得 wrapper 看起來更像原來的函數):
def typecheck(f):
def do_typecheck(name, arg):
expected_type = f.__annotations__.get(name, None)
if expected_type and not isinstance(arg, expected_type):
raise RuntimeError("{} should be of type {} instead of {}".format(name, expected_type.__name__, type(arg).__name__))
@functools.wraps(f)
def wrapper(*args, **kwargs):
for i, arg in enumerate(args[:f.__code__.co_nlocals]):
do_typecheck(f.__code__.co_varnames[i], arg)
for name, arg in kwargs.items():
do_typecheck(name, arg)
result = f(*args, **kwargs)
do_typecheck('return', result)
return result
return wrapper
結論
註解是 Python 3 中的一個新元素,本文例子中的使用方法很普通,你也可以想像很多特定領域的應用。雖然上面的實現代碼並不能滿足實際產品要求,但它的目的本來就是用作概念驗證。可以對其進行以下改善:
處理額外的參數( args 中意想不到的項目)
默認值類型檢查
支持多個類型
支持模板類型(例如,int 型列表)