Python3 OOP(四) 获取对象信息
生活随笔
收集整理的這篇文章主要介紹了
Python3 OOP(四) 获取对象信息
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
使用type()
1:判斷對象類型,使用type()函數 eg:
res = type(123)print(res) #<lass 'int'>2:如果一個變量指向函數或者類,也可以用type()判斷
res = type(abs) print(res) #<class 'builtin_function_or_method'>class M(object):def __init__(self, name, age):self.name = nameself.age = age a = M('小明',12) print(type(a)) #<class '__main__.M'>3:但是type()函數返回的是什么類型呢?它返回對應的Class類型。如果我們要在if語句中判斷,就需要比較兩個變量的type類型是否相同:
res = type(123)==type(456) print(res) #True res2 = type(123)==int print(res2) #True res3 = type('abc')==type('123') print(res3) #True res4 = type('abc')==str print(res4) #True res5 = type('abc')==type(123) print(res5) #False4:判斷基本數據類型可以直接寫int,str等,但如果要判斷一個對象是否是函數怎么辦?可以使用types模塊中定義的常量:
import types def fn():pass res = type(fn)==types.FunctionType print(res) #True res2 = type(abs)==types.BuiltinFunctionType print(res2) #True res3 = type(lambda x: x)==types.LambdaType print(res3) #True res4 = type((x for x in range(10)))==types.GeneratorType print(res4) #True使用isinstance()
對于class的繼承關系來說,使用type()就很不方便。我們要判斷class的類型,可以使用isinstance()函數。
........待續。。
?
轉載于:https://www.cnblogs.com/gjh99/p/11182182.html
總結
以上是生活随笔為你收集整理的Python3 OOP(四) 获取对象信息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET MVC3源码下载
- 下一篇: 2019_7_30python