Python Class Variables With Examples - PYnative

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

In Python, Class variables are declared when a class is being ... Access class variable inside instance method by using either self of class ... Home»Python»PythonObject-OrientedProgramming(OOP)»PythonClassVariables InObject-orientedprogramming,whenwedesignaclass,weuseinstancevariablesandclassvariables. InClass,attributescanbedefinedintotwoparts: Instancevariables:Ifthevalueofavariablevariesfromobjecttoobject,thensuchvariablesarecalledinstancevariables.ClassVariables:Aclassvariableisavariablethatisdeclaredinsideofclass,butoutsideofanyinstancemethodor __init__() method. Afterreadingthisarticle,you’lllearn: HowtocreateandaccessclassvariablesModifyvaluesofaclassvariablesInstancevariablevs.classvariablesBehaviourofaclassvariableininheritance TableofcontentsWhatisanClassVariableinPython?CreateClassVariablesAccessingClassVariablesModifyClassVariablesClassVariablevsInstancevariablesClassVariablesInInheritanceWrongUseofClassVariables WhatisanClassVariableinPython? Ifthevalueofavariableisnotvariedfromobjecttoobject,suchtypesofvariablesarecalledclassvariablesorstaticvariables. Classvariablesaresharedbyallinstancesofaclass.Unlikeinstancevariable,thevalueofaclassvariableisnotvariedfromobjecttoobject, InPython,Classvariablesaredeclaredwhenaclassisbeingconstructed.Theyarenotdefinedinsideanymethodsofaclassbecauseofthisonlyonecopyofthestaticvariablewillbecreatedandsharedbetweenallobjectsoftheclass. Forexample,inStudentclass,wecanhavedifferentinstancevariablessuchasnameandrollnumberbecauseeachstudent’snameandrollnumberaredifferent. But,ifwewanttoincludetheschoolnameinthestudentclass,wemustusetheclassvariableinsteadofaninstancevariableastheschoolnameisthesameforallstudents.Soinsteadofmaintainingtheseparatecopyineachobject,wecancreateaclassvariablethatwillholdtheschoolnamesoallstudents(objects)canshareit. Wecanaddanynumberofclassvariablesinaclass. UnderstandClassVariables CreateClassVariables Aclassvariableisdeclaredinsideofclass,butoutsideofanyinstancemethodor __init__() method. Byconvention,typicallyitisplacedrightbelowtheclassheaderandbeforetheconstructormethodandothermethods. Example: classStudent: #Classvariable school_name='ABCSchool' def__init__(self,name,roll_no): self.name=name self.roll_no=roll_no #createfirstobject s1=Student('Emma',10) print(s1.name,s1.roll_no,Student.school_name) #accessclassvariable #createsecondobject s2=Student('Jessa',20) #accessclassvariable print(s2.name,s2.roll_no,Student.school_name) Output Emma10ABCSchool Jessa20ABCSchool Intheaboveexample,wecreatedtheclassvariableschool_nameandaccesseditusingtheobjectandclassname. Note:Likeregularvariables,classvariablescanstoredataofanytype.WecanusePythonlist,Pythontuple,andPythondictionaryasaclassvariable. AccessingClassVariables Wecanaccessstaticvariableseitherbyclassnameorbyobjectreference,butitisrecommendedtousetheclassname. InPython,wecanaccesstheclassvariableinthefollowingplaces Accessinsidetheconstructorbyusingeitherselfparameterorclassname.AccessclassvariableinsideinstancemethodbyusingeitherselfofclassnameAccessfromoutsideofclassbyusingeitherobjectreferenceorclassname. Example1:AccessClassVariableintheconstructor classStudent: #Classvariable school_name='ABCSchool' #constructor def__init__(self,name): self.name=name #accessclassvariableinsideconstructorusingself print(self.school_name) #accessusingclassname print(Student.school_name) #createObject s1=Student('Emma') Output ABCSchool ABCSchool Example2:AccessClassVariableinInstancemethodandoutsideclass classStudent: #Classvariable school_name='ABCSchool' #constructor def__init__(self,name,roll_no): self.name=name self.roll_no=roll_no #Instancemethod defshow(self): print('Insideinstancemethod') #accessusingself print(self.name,self.roll_no,self.school_name) #accessusingclassname print(Student.school_name) #createObject s1=Student('Emma',10) s1.show() print('Outsideclass') #accessclassvariableoutsideclass #accessusingobjectreference print(s1.school_name) #accessusingclassname print(Student.school_name) Output Insideinstancemethod Emma10ABCSchool ABCSchool Outsideclass ABCSchool ABCSchool Inthisexample,weaccessedtheclassvariableschool_nameusingclassnameandaselfkeywordinsideamethod. ModifyClassVariables Generally,weassignvaluetoaclassvariableinsidetheclassdeclaration.However,wecanchangethevalueoftheclassvariableeitherintheclassoroutsideofclass. Note:Weshouldchangetheclassvariable’svalueusingtheclassnameonly. Example classStudent: #Classvariable school_name='ABCSchool' #constructor def__init__(self,name,roll_no): self.name=name self.roll_no=roll_no #Instancemethod defshow(self): print(self.name,self.roll_no,Student.school_name) #createObject s1=Student('Emma',10) print('Before') s1.show() #Modifyclassvariable Student.school_name='XYZSchool' print('After') s1.show() Output: Before Emma10ABCSchool After Emma10XYZSchool Note: Itisbestpracticetouseaclassnametochangethevalueofaclassvariable.Becauseifwetrytochangetheclassvariable’svaluebyusinganobject,anewinstancevariableiscreatedforthatparticularobject,whichshadowstheclassvariables. Example: classStudent: #Classvariable school_name='ABCSchool' #constructor def__init__(self,name,roll_no): self.name=name self.roll_no=roll_no #createObjects s1=Student('Emma',10) s2=Student('Jessa',20) print('Before') print(s1.name,s1.roll_no,s1.school_name) print(s2.name,s2.roll_no,s2.school_name) #Modifyclassvariableusingobjectreference s1.school_name='PQRSchool' print('After') print(s1.name,s1.roll_no,s1.school_name) print(s2.name,s2.roll_no,s2.school_name) Output: Before Emma10ABCSchool Jessa20ABCSchool After Emma10PQRSchool Jessa20ABCSchool Anewinstancevariableiscreatedforthes1object,andthisvariableshadowstheclassvariables.Soalwaysusetheclassnametomodifytheclassvariable. ClassVariablevsInstancevariables Thefollowingtableshowsthedifferencebetweentheinstancevariableandtheclassvariable. InPython,propertiescanbedefinedintotwoparts: Instancevariables:Instancevariable’svaluevariesfromobjecttoobject.Instancevariablesarenotsharedbyobjects.EveryobjecthasitsowncopyoftheinstanceattributeClassVariables:Aclassvariableisavariablethatisdeclaredinsideofclass,butoutsideofanyinstancemethodor __init__() method.Classvariablesaresharedbyallinstancesofaclass. ReadMore:InstancevariablesinPythonwithExamples InstanceVariableClassVariableInstancevariablesarenotsharedbyobjects.EveryobjecthasitsowncopyoftheinstanceattributeClassvariablesaresharedbyallinstances.Instancevariablesaredeclaredinsidetheconstructori.e.,the__init__()method.Classvariablesaredeclaredinsidetheclassdefinitionbutoutsideanyoftheinstancemethodsandconstructors.Itisgetscreatedwhenaninstanceoftheclassiscreated.Itiscreatedwhentheprogrambeginstoexecute.Changesmadetothesevariablesthroughoneobjectwillnotreflectinanotherobject.Changesmadeintheclassvariablewillreflectinallobjects.ClassVariablesvs.InstanceVariables Example: Let’sseetheexampletocreateaclassvariableandinstancevariable. classCar: #Classvariable manufacturer='BMW' def__init__(self,model,price): #instancevariable self.model=model self.price=price #createObject car=Car('x1',2500) print(car.model,car.price,Car.manufacturer) Output: x12500BMW ClassVariablesInInheritance Asyouknow,onlyonecopyoftheclassvariablewillbecreatedandsharedbetweenallobjectsofthatclass. Whenweuseinheritance,allvariablesandmethodsofthebaseclassareavailabletothechildclass.Insuchcases,Wecanalsochangethevalueoftheparentclass’sclassvariableinthechildclass. Wecanusetheparentclassorchildclassnametochangethevalueofaparentclass’sclassvariableinthechildclass. Example classCourse: #classvariable course="Python" classStudent(Course): def__init__(self,name): self.name=name defshow_student(self): #Accessingclassvariableofparentclass print('Before') print("Studentname:",self.name,"CourseName:",Student.course) #changingclassvariablevalueofbaseclass print('Now') Student.course="MachineLearning" print("Studentname:",self.name,"CourseName:",Student.course) #creatingobjectofStudentclass stud=Student("Emma") stud.show_student() Output Before Studentname:EmmaCourseName:Python Now Studentname:EmmaCourseName:MachineLearning Whatifbothchildclassandparentclasshasthesameclassvariablename.Inthiscase,thechildclasswillnotinherittheclassvariableofabaseclass.Soitisrecommendedtocreateaseparateclassvariableforchildclassinsteadofinheritingthebaseclassvariable. Example: classCourse: #classvariable course="Python" classStudent(Course): #classvariable course="SQL" def__init__(self,name): self.name=name defshow_student(self): #Accessingclassvariable print('Before') print("Studentname:",self.name,"CourseName:",Student.course) #changingclassvariable'svalue print('Now') Student.course="MachineLearning" print("Studentname:",self.name,"CourseName:",Student.course) #creatingobjectofStudentclass stud=Student("Emma") stud.show_student() #parentclasscoursename print('ParentClassCourseName:',Course.course) Output: Before Studentname:EmmaCourseName:SQL Now Studentname:EmmaCourseName:MachineLearning ParentClassCourseName:Python WrongUseofClassVariables InPython,weshouldproperlyusetheclassvariablebecauseallobjectssharethesamecopy.Thus,ifoneoftheobjectsmodifiesthevalueofaclassvariable,thenallobjectsstartreferringtothefreshcopy. Forexample, Example classPlayer: #classvariables club='Chelsea' sport='Football' def__init__(self,name): #Instancevariable self.name=name defshow(self): print("Player:",'Name:',self.name,'Club:',self.club,'Sports:',self.sport) p1=Player('John') #wronguseofclassvariable p1.club='FC' p1.show() p2=Player('Emma') p2.sport='Tennis' p2.show() #actualclassvariablevalue print('Club:',Player.club,'Sport:',Player.sport) Output Player:Name:JohnClub:FCSports:Football Player:Name:EmmaClub:ChelseaSports:Tennis Club:ChelseaSport:Football Intheaboveexample,theinstancevariablenameisuniqueforeachplayer.Theclassvariableteamandsportcanbeaccessedandmodifiedbyanyobject. Becausebothobjectsmodifiedtheclassvariable,anewinstancevariableiscreatedforthatparticularobjectwiththesamenameastheclassvariable,whichshadowstheclassvariables. Inourcase,forobjectp1newinstancevariableclubgetscreated,andforobjectp2newinstancevariablesportgetscreated. Sowhenyoutrytoaccesstheclassvariableusingthep1orp2object,itwillnotreturntheactualclassvariablevalue. Toavoidthis,alwaysmodifytheclassvariablevalueusingtheclassnamesothatallobjectsgetstheupdatedvalue.Likethis Player.club='FC' Player.sport='Tennis' Didyoufindthispagehelpful?Letothersknowaboutit.SharinghelpsmecontinuetocreatefreePythonresources. TweetF sharein shareP Pin AboutVishal FounderofPYnative.comIamaPythondeveloperandIlovetowritearticlestohelpdevelopers.FollowmeonTwitter.AllthebestforyourfuturePythonendeavors! RelatedTutorialTopics: PythonPythonObject-OrientedProgramming(OOP) PythonExercisesandQuizzes FreecodingexercisesandquizzescoverPythonbasics,datastructure,dataanalytics,andmore. 15+Topic-specificExercisesandQuizzesEachExercisecontains10questionsEachQuizcontains12-15MCQ Exercises Quizzes PostedIn PythonPythonObject-OrientedProgramming(OOP) TweetF sharein shareP Pin PythonOOP PythonOOP ClassesandObjectsinPython ConstructorsinPython PythonDestructors EncapsulationinPython PolymorphisminPython InheritanceinPython PythonInstanceVariables PythonInstanceMethods PythonClassVariables PythonClassMethod PythonStaticMethod PythonClassMethodvs.StaticMethodvs.InstanceMethod PythonOOPexercise AllPythonTopics PythonBasics PythonExercises PythonQuizzes PythonFileHandling PythonOOP PythonDateandTime PythonRandom PythonRegex PythonPandas PythonDatabases PythonMySQL PythonPostgreSQL PythonSQLite PythonJSON AboutPYnative PYnative.comisforPythonlovers.Here,YoucangetTutorials,Exercises,andQuizzestopracticeandimproveyourPythonskills. ExplorePython LearnPython PythonBasics PythonDatabases PythonExercises PythonQuizzes OnlinePythonCodeEditor PythonTricks FollowUs TogetNewPythonTutorials,Exercises,andQuizzes Twitter Facebook Sitemap LegalStuff AboutUs ContactUs Weusecookiestoimproveyourexperience.WhileusingPYnative,youagreetohavereadandacceptedourTermsOfUse,CookiePolicy,andPrivacyPolicy. Copyright© 2018–2022pynative.com Searchfor:SearchButton



請為這篇文章評分?