type() and isinstance() in Python with Examples - Guru99

文章推薦指數: 80 %
投票人數:10人

Python has a built-in function called type() that helps you find the class type of the variable given as input. For example, if the input is a ... Skiptocontent Whatistype()inPython? Pythonhasabuilt-infunctioncalledtype()thathelpsyoufindtheclasstypeofthevariablegivenasinput.Forexample,iftheinputisastring,youwillgettheoutputas,forthelist,itwillbe,etc. Usingtype()command,youcanpassasingleargument,andthereturnvaluewillbetheclasstypeoftheargumentgiven,example:type(object). Itisalsopossibletopassthreeargumentstotype(),i.e.,type(name,bases,dict),insuchcase,itwillreturnyouanewtypeobject. Inthistutorial,youwilllearn: Whatistype()inPython? Syntaxfortype(): Exampleoftype() Example:Usingtype()forclassobject. Example:Usingthename,bases,anddictintype() Whatisisinstance()inPython? Syntaxisinstance(): Examplesofisinstance() DifferenceBetweentype()andisinstance()inPython Syntaxfortype(): type()canbeusedintwowaysasshownbelow: type(object) type(namr,bases,dict) Parameters:type(object) object:Thisisamandatoryparameter.Ifthisisonlyparameterpassedtotype(),thanitwillreturnyouthetypeoftheparameter. Parameters:type(name,bases,dict) name:nameoftheclass. bases:(optional).Thisisanoptionalparameter,anditisthebaseclass dict:(optional).Thisisanoptionalparameter,anditisanamespacethathasthedefinitionoftheclass. ReturnValue: Iftheobjectistheonlyparameterpassedtotype()thenitwillreturnyouthetypeoftheobject. Iftheparamspassedtotypeisatype(object,bases,dict),insuchcase,itwillreturnanewtypeofobject. Exampleoftype() Inthis,examplewehaveastringvalue,number,floatvalue,acomplexnumber,list,tuple,dictandset.Wewillusethevariableswithtypetoseetheoutputforeachofthem. str_list="WelcometoGuru99" age=50 pi=3.14 c_num=3j+10 my_list=["A","B","C","D"] my_tuple=("A","B","C","D") my_dict={"A":"a","B":"b","C":"c","D":"d"} my_set={'A','B','C','D'} print("Thetypeis:",type(str_list)) print("Thetypeis:",type(age)) print("Thetypeis:",type(pi)) print("Thetypeis:",type(c_num)) print("Thetypeis:",type(my_list)) print("Thetypeis:",type(my_tuple)) print("Thetypeis:",type(my_dict)) print("Thetypeis:",type(my_set)) Output: Thetypeis: Thetypeis: Thetypeis: Thetypeis: Thetypeis: Thetypeis: Thetypeis: Thetypeis: Example:Usingtype()forclassobject. Whenyouchecktheobjectcreatedfromaclassusingtype(),itreturnstheclasstypealongwiththenameoftheclass.Inthisexample,wewillcreateaclassandchecktheobjecttypecreatedfromtheclasstest. classtest: s='testing' t=test() print(type(t)) Output: Example:Usingthename,bases,anddictintype() Thetypecanbealsocalledusingthesyntax:type(name,bases,dict). Thethreeparameterspassedtotype()i.e.,name,basesanddictarethecomponentsthatmakeupaclassdefinition.Thenamerepresentstheclassname,thebasesisthebaseclass,anddictisthedictionaryofbaseclassattributes. Inthisexample,wearegoingtomakeuseofallthreeparamsi.ename,bases,anddictintype(). Example: classMyClass: x='HelloWorld' y=50 t1=type('NewClass',(MyClass,),dict(x='HelloWorld',y=50)) print(type(t1)) print(vars(t1)) Output: {'x':'HelloWorld','y':50,'__module__':'__main__','__doc__':None} Whenyoupassallthreeargumentstotype(),ithelpsyoutoinitializenewclasswithbaseclassattributes. Whatisisinstance()inPython? Pythonisinstanceispartofpythonbuilt-infunctions.Pythonisinstance()takesintwoarguments,anditreturnstrueifthefirstargumentisaninstanceoftheclassinfogivenasthesecondargument. Syntaxisinstance() isinstance(object,classtype) Parameters object:Anobjectwhoseinstanceyouarecomparingwithclasstype.Itwillreturntrueifthetypematchesotherwisefalse. classtype:Atypeoraclassoratupleoftypesand/orclasses. Returnvalue: Itwillreturntrueiftheobjectisaninstanceofclasstypeandfalseifnot. Examplesofisinstance() Inthissection,wewillstudyvariousexamplestolearnisinstance() Example:isinstance()Integercheck Thecodebelowcomparesintegervalue51withtypeint.Itwillreturntrueitthetypeof51matcheswithintotherwisefalse. age=isinstance(51,int) print("ageisaninteger:",age) Output: ageisaninteger:True Example:isinstance()Floatcheck Inthisexamplewearegoingtocomparethefloatvaluewithtypefloati.e.3.14valuewillbecomparewithtypefloat. pi=isinstance(3.14,float) print("piisafloat:",pi) Output: piisafloat:True Example:isinstance()Stringcheck message=isinstance("HelloWorld",str) print("messageisastring:",message) Output: messageisastring:True Example:isinstance()Tuplecheck Thecodechecksforatuple(1,2,3,4,5)withtypetuple.Itwillreturntrueiftheinputgivenisoftypetupleandfalseifnot. my_tuple=isinstance((1,2,3,4,5),tuple) print("my_tupleisatuple:",my_tuple) Output: my_tupleisatuple:True Example:isinstance()Setcheck Thecodechecksforaset({1,2,3,4,5},withtypeset.Itwillreturntrueiftheinputgivenisoftypesetandfalseifnot. my_set=isinstance({1,2,3,4,5},set) print("my_setisaset:",my_set) Output: my_setisaset:True Example:isinstance()listcheck Thecodechecksforalist[1,2,3,4,5],withtypelist.Itwillreturntrueiftheinputgivenisoftypelistandfalseifnot. my_list=isinstance([1,2,3,4,5],list) print("my_listisalist:",my_list) Output: my_listisalist:True Example:isinstance()dictcheck Thecodechecksforadict({“A”:”a”,“B”:”b”,“C”:”c”,“D”:”d”},withtypedict.Itwillreturntrueiftheinputgivenisoftypedictandfalseifnot. my_dict=isinstance({"A":"a","B":"b","C":"c","D":"d"},dict) print("my_dictisadict:",my_dict) Output: my_dictisadict:True Example:isinstance()testonaclass Thecodeshowsthetypecheckofclasswithisinstance().Theobjectoftheclassiscomparedwiththenameoftheclassinsideisinstance().Itreturnstrueiftheobjectbelongstotheclassandfalseotherwise. classMyClass: _message="HelloWorld" _class=MyClass() print("_classisainstanceofMyClass():",isinstance(_class,MyClass)) Output: _classisainstanceofMyClass()True DifferenceBetweentype()andisinstance()inPython type() isinstance() Pythonhasabuilt-infunctioncalledtype()thathelpsyoufindtheclasstypeofthevariablegivenasinput. Pythonhasabuilt-infunctioncalledisinstance()thatcomparesthevaluewiththetypegiven.Ifthevalueandtypegivenmatchesitwillreturntrueotherwisefalse. Thereturnvalueisatypeobject ThereturnvalueisaBooleani.etrueorfalse. classA: my_listA=[1,2,3] classB(A): my_listB=[1,2,3] print(type(A())==A) print(type(B())==A) Output: True False Incaseoftypethesubclasscheckgivesbackfalse. classA: my_listA=[1,2,3] classB(A): my_listB=[1,2,3] print(isinstance(A(),A)) print(isinstance(B(),A)) Output: True True isinstance()givesatruthyvaluewhencheckedwithasubclass. Summary: Pythonhasabuilt-infunctioncalledtype()thathelpsyoufindtheclasstypeofthevariablegivenasinput.Forexample,iftheinputisastring,youwillgettheoutputas,forthelist,itwillbe,etc. Fortype(),youcanpassasingleargument,andthereturnvaluewillbetheclasstypeoftheargumentgiven,e.g.,type(object). Itisalsopossibletopassthreeargumentstotype(),i.e.,type(name,bases,dict),insuchcase,itwillreturnyouanewtypeobject. Pythonhasabuilt-infunctioncalledinstance()thatcomparesthevaluewiththetypegiven.Itthevalueandtypegivenmatchesitwillreturntrueotherwisefalse.Usingisinstance(),youcantestforstring,float,int,list,tuple,dict,set,class,etc. Usingisinstance()method,youcantestforstring,float,int,list,tuple,dict,set,class,etc. YouMightLike: PythonVariables:HowtoDefine/DeclareStringVariableTypes PythonStrings:Replace,Join,Split,Reverse,Uppercase&Lowercase PythonCALENDARTutorialwithExample 10BESTPythonIDE&CodeEditorsforWindows,Linux&Mac PythonDictionaryAppend:HowtoAddKey/ValuePair Postnavigation ReportaBug Previous PrevNextContinue Scrolltotop ToggleMenuClose Searchfor: Search



請為這篇文章評分?