Python Classes and Objects [With Examples] - Programiz

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

Like function definitions begin with the def keyword in Python, class definitions begin with a class keyword. The first string inside the class is called ... CourseIndex ExploreProgramiz Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnPythonpractically andGetCertified. ENROLL PopularTutorials GettingStartedWithPython PythonifStatement whileLoopinPython PythonLists DictionariesinPython StartLearningPython PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear ExplorePythonExamples ReferenceMaterials Built-inFunctions ListMethods DictionaryMethods StringMethods Viewall LearningPaths Challenges LearnPythonInteractively TryforFree Courses BecomeaPythonMaster BecomeaCMaster BecomeaJavaMaster ViewallCourses Python JavaScript SQL C C++ Java Kotlin Swift C# DSA LearnPythonpractically andGetCertified. ENROLLFORFREE! PopularTutorials GettingStartedWithPython PythonifStatement whileLoopinPython PythonLists DictionariesinPython StartLearningPython AllPythonTutorials ReferenceMaterials Built-inFunctions ListMethods DictionaryMethods StringMethods Viewall Python JavaScript C C++ Java Kotlin LearnPythonpractically andGetCertified. ENROLLFORFREE! PopularExamples Addtwonumbers Checkprimenumber Findthefactorialofanumber PrinttheFibonaccisequence Checkleapyear AllPythonExamples LearnPythonInteractively PythonIntroduction GettingStarted KeywordsandIdentifier Statements&Comments PythonVariables PythonDataTypes PythonTypeConversion PythonI/OandImport PythonOperators PythonNamespace PythonFlowControl Pythonif...else PythonforLoop PythonwhileLoop Pythonbreakandcontinue PythonPass PythonFunctions PythonFunction FunctionArgument PythonRecursion AnonymousFunction Global,LocalandNonlocal PythonGlobalKeyword PythonModules PythonPackage PythonDatatypes PythonNumbers PythonList PythonTuple PythonString PythonSet PythonDictionary PythonFiles PythonFileOperation PythonDirectory PythonException ExceptionHandling User-definedException PythonObject&Class PythonOOP PythonClass PythonInheritance MultipleInheritance OperatorOverloading PythonAdvancedTopics PythonIterator PythonGenerator PythonClosure PythonDecorators PythonProperty PythonRegEx PythonExamples PythonDateandtime PythondatetimeModule Pythondatetime.strftime() Pythondatetime.strptime() Currentdate&time Getcurrenttime Timestamptodatetime PythontimeModule Pythontime.sleep() RelatedTopics PythonObjectOrientedProgramming Pythongetattr() Pythonhasattr() PythonFunctionArguments Pythonsetattr() PythonDocstrings PythonObjectsandClasses Inthistutorial,youwilllearnaboutthecorefunctionalityofPythonobjectsandclasses.You'lllearnwhataclassis,howtocreateitanduseitinyourprogram. Video:PythonClassesandObjects PythonObjectsandClasses Pythonisanobject-orientedprogramminglanguage.Unlikeprocedure-orientedprogramming,wherethemainemphasisisonfunctions,object-orientedprogrammingstressesonobjects. Anobjectissimplyacollectionofdata(variables)andmethods(functions)thatactonthosedata.Similarly,aclassisablueprintforthatobject. Wecanthinkofaclassasasketch(prototype)ofahouse.Itcontainsallthedetailsaboutthefloors,doors,windows,etc.Basedonthesedescriptionswebuildthehouse.Houseistheobject. Asmanyhousescanbemadefromahouse'sblueprint,wecancreatemanyobjectsfromaclass.Anobjectisalsocalledaninstanceofaclassandtheprocessofcreatingthisobjectiscalledinstantiation. DefiningaClassinPython LikefunctiondefinitionsbeginwiththedefkeywordinPython,classdefinitionsbeginwithaclasskeyword. Thefirststringinsidetheclassiscalleddocstringandhasabriefdescriptionoftheclass.Althoughnotmandatory,thisishighlyrecommended. Hereisasimpleclassdefinition. classMyNewClass: '''Thisisadocstring.Ihavecreatedanewclass''' pass Aclasscreatesanewlocalnamespacewhereallitsattributesaredefined.Attributesmaybedataorfunctions. Therearealsospecialattributesinitthatbeginswithdoubleunderscores__.Forexample,__doc__givesusthedocstringofthatclass. Assoonaswedefineaclass,anewclassobjectiscreatedwiththesamename.Thisclassobjectallowsustoaccessthedifferentattributesaswellastoinstantiatenewobjectsofthatclass. classPerson: "Thisisapersonclass" age=10 defgreet(self): print('Hello') #Output:10 print(Person.age) #Output: print(Person.greet) #Output:"Thisisapersonclass" print(Person.__doc__) Output 10 Thisisapersonclass CreatinganObjectinPython Wesawthattheclassobjectcouldbeusedtoaccessdifferentattributes. Itcanalsobeusedtocreatenewobjectinstances(instantiation)ofthatclass.Theproceduretocreateanobjectissimilartoafunctioncall. >>>harry=Person() Thiswillcreateanewobjectinstancenamedharry.Wecanaccesstheattributesofobjectsusingtheobjectnameprefix. Attributesmaybedataormethod.Methodsofanobjectarecorrespondingfunctionsofthatclass. Thismeanstosay,sincePerson.greetisafunctionobject(attributeofclass),Person.greetwillbeamethodobject. classPerson: "Thisisapersonclass" age=10 defgreet(self): print('Hello') #createanewobjectofPersonclass harry=Person() #Output: print(Person.greet) #Output:> print(harry.greet) #Callingobject'sgreet()method #Output:Hello harry.greet() Output > Hello Youmayhavenoticedtheselfparameterinfunctiondefinitioninsidetheclassbutwecalledthemethodsimplyasharry.greet()withoutanyarguments.Itstillworked. Thisisbecause,wheneveranobjectcallsitsmethod,theobjectitselfispassedasthefirstargument.So,harry.greet()translatesintoPerson.greet(harry). Ingeneral,callingamethodwithalistofnargumentsisequivalenttocallingthecorrespondingfunctionwithanargumentlistthatiscreatedbyinsertingthemethod'sobjectbeforethefirstargument. Forthesereasons,thefirstargumentofthefunctioninclassmustbetheobjectitself.Thisisconventionallycalledself.Itcanbenamedotherwisebutwehighlyrecommendtofollowtheconvention. Nowyoumustbefamiliarwithclassobject,instanceobject,functionobject,methodobjectandtheirdifferences. ConstructorsinPython Classfunctionsthatbeginwithdoubleunderscore__arecalledspecialfunctionsastheyhavespecialmeaning. Ofoneparticularinterestisthe__init__()function.Thisspecialfunctiongetscalledwheneveranewobjectofthatclassisinstantiated. ThistypeoffunctionisalsocalledconstructorsinObjectOrientedProgramming(OOP).Wenormallyuseittoinitializeallthevariables. classComplexNumber: def__init__(self,r=0,i=0): self.real=r self.imag=i defget_data(self): print(f'{self.real}+{self.imag}j') #CreateanewComplexNumberobject num1=ComplexNumber(2,3) #Callget_data()method #Output:2+3j num1.get_data() #CreateanotherComplexNumberobject #andcreateanewattribute'attr' num2=ComplexNumber(5) num2.attr=10 #Output:(5,0,10) print((num2.real,num2.imag,num2.attr)) #butc1objectdoesn'thaveattribute'attr' #AttributeError:'ComplexNumber'objecthasnoattribute'attr' print(num1.attr) Output 2+3j (5,0,10) Traceback(mostrecentcalllast): File"",line27,in print(num1.attr) AttributeError:'ComplexNumber'objecthasnoattribute'attr' Intheaboveexample,wedefinedanewclasstorepresentcomplexnumbers.Ithastwofunctions,__init__()toinitializethevariables(defaultstozero)andget_data()todisplaythenumberproperly. Aninterestingthingtonoteintheabovestepisthatattributesofanobjectcanbecreatedonthefly.Wecreatedanewattributeattrforobjectnum2andreaditaswell.Butthisdoesnotcreatethatattributeforobjectnum1. DeletingAttributesandObjects Anyattributeofanobjectcanbedeletedanytime,usingthedelstatement.TrythefollowingonthePythonshelltoseetheoutput. >>>num1=ComplexNumber(2,3) >>>delnum1.imag >>>num1.get_data() Traceback(mostrecentcalllast): ... AttributeError:'ComplexNumber'objecthasnoattribute'imag' >>>delComplexNumber.get_data >>>num1.get_data() Traceback(mostrecentcalllast): ... AttributeError:'ComplexNumber'objecthasnoattribute'get_data' Wecanevendeletetheobjectitself,usingthedelstatement. >>>c1=ComplexNumber(1,3) >>>delc1 >>>c1 Traceback(mostrecentcalllast): ... NameError:name'c1'isnotdefined Actually,itismorecomplicatedthanthat.Whenwedoc1=ComplexNumber(1,3),anewinstanceobjectiscreatedinmemoryandthenamec1bindswithit. Onthecommanddelc1,thisbindingisremovedandthenamec1isdeletedfromthecorrespondingnamespace.Theobjecthowevercontinuestoexistinmemoryandifnoothernameisboundtoit,itislaterautomaticallydestroyed. ThisautomaticdestructionofunreferencedobjectsinPythonisalsocalledgarbagecollection. DeletingobjectsinPythonremovesthenamebinding TableofContents PythonObjectsandClasses DefiningaClassinPython CreatinganObjectinPython ConstructorsinPython DeletingAttributesandObjects PreviousTutorial: PythonOOP NextTutorial: PythonInheritance Shareon: Didyoufindthisarticlehelpful? Sorryaboutthat. Howcanweimproveit? Feedback* Leavethisfieldblank RelatedTutorialsPythonLibraryPythongetattr()PythonLibraryPythonhasattr()PythonLibraryPythonsetattr()PythonTutorialPythonObjectOrientedProgramming TryPROforFREE LearnPythonInteractively



請為這篇文章評分?