Python property() function - GeeksforGeeks
文章推薦指數: 80 %
Python property() function ... Python property() function returns the object of the property class and it is used to create property of a class. Skiptocontent TutorialsPracticeDS&Algo.MustDoQuestionsDSATopic-wiseDSACompany-wiseAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsGeekontheTopCareersInternshipJobsApplyforJobsPostaJobJOB-A-THONEventsCourses ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningWebDevelopmentSDESheetPuzzlesGFGSchoolProjects RelatedArticles ▲RelatedArticlesPythonPropertyDecorator–@propertyPythonproperty()functionGetterandSetterinPythonPrintSingleandMultiplevariableinPythonSwapTwoVariablesinOneLinePrivateVariablesinPython__name__(ASpecialvariable)inPythonPythonOperatorsG-Fact19(LogicalandBitwiseNotOperatorsonBoolean)TernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1OperatorFunctionsinPython|Set2Differencebetween==andisoperatorinPythonPythonMembershipandIdentityOperatorsPython|Set3(Strings,Lists,Tuples,Iterations)PythonStringPythonListsPythonTuplesPythonSetsPythonDictionaryPythonArraysPython|Using2Darrays/liststherightwayAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadJSONfileusingPythonTableofContentsPythonPropertyDecorator–@propertyPythonproperty()functionGetterandSetterinPythonPrintSingleandMultiplevariableinPythonSwapTwoVariablesinOneLinePrivateVariablesinPython__name__(ASpecialvariable)inPythonPythonOperatorsG-Fact19(LogicalandBitwiseNotOperatorsonBoolean)TernaryOperatorinPythonDivisionOperatorsinPythonOperatorOverloadinginPythonAnyAllinPythonOperatorFunctionsinPython|Set1OperatorFunctionsinPython|Set2Differencebetween==andisoperatorinPythonPythonMembershipandIdentityOperatorsPython|Set3(Strings,Lists,Tuples,Iterations)PythonStringPythonListsPythonTuplesPythonSetsPythonDictionaryPythonArraysPython|Using2Darrays/liststherightwayAddingnewcolumntoexistingDataFrameinPandasPythonmap()functionTakinginputinPythonHowtogetcolumnnamesinPandasdataframeReadJSONfileusingPythonImproveArticle SaveArticle LikeArticle Pythonproperty()functionDifficultyLevel: ExpertLastUpdated: 23Sep,2021Pythonproperty()functionreturnstheobjectofthepropertyclassanditisusedtocreatepropertyofaclass. Syntax:property(fget,fset,fdel,doc)Parameters: fget()–usedtogetthevalueofattributefset()–usedtosetthevalueofattributefdel()–usedtodeletetheattributevaluedoc()–stringthatcontainsthedocumentation(docstring)fortheattributeReturn:Returnsapropertyattributefromthegivengetter,setteranddeleter.Note: Ifnoargumentsaregiven,property()methodreturnsabasepropertyattributethatdoesn’tcontainanygetter,setterordeleter.Ifdocisn’tprovided,property()methodtakesthedocstringofthegetterfunction.Example#1:Usingproperty()method Python3#Pythonprogramtoexplainproperty()function#Alphabetclass classAlphabet: def__init__(self,value): self._value=value #gettingthevalues defgetValue(self): print('Gettingvalue') returnself._value #settingthevalues defsetValue(self,value): print('Settingvalueto'+value) self._value=value #deletingthevalues defdelValue(self): print('Deletingvalue') delself._value value=property(getValue,setValue, delValue,) #passingthevaluex=Alphabet('GeeksforGeeks')print(x.value) x.value='GfG' delx.valueOutput: Gettingvalue GeeksforGeeks SettingvaluetoGfG DeletingvaluePythonpropertyUsingDecoratorThemainworkofdecoratorsistheyareusedtoaddfunctionalitytotheexistingcode.Alsocalledmetaprogramming,asapartoftheprogramtriestomodifyanotherpartoftheprogramatcompiletime.Example#2:Using@propertydecoratorPython3#Pythonprogramtoexplainproperty()#functionusingdecorator classAlphabet: def__init__(self,value): self._value=value #gettingthevalues @property defvalue(self): print('Gettingvalue') returnself._value #settingthevalues @value.setter defvalue(self,value): print('Settingvalueto'+value) self._value=value #deletingthevalues @value.deleter defvalue(self): print('Deletingvalue') delself._value #passingthevaluex=Alphabet('Peter')print(x.value) x.value='Diesel' delx.valueOutput: Gettingvalue Peter SettingvaluetoDiesel DeletingvalueUsing@propertydecoratorworkssameasproperty()method.First,specifythatvalue()methodisalsoanattributeofAlphabetthen,weusetheattributevaluetospecifythePythonpropertysetterandthedeleter.Noticethatthesamemethodvalue()isusedwithdifferentdefinitionsfordefiningthegetter,setter,anddeleter.Wheneverweusex.value,itinternallycallstheappropriategetter,setter,anddeleter.PythonpropertyvsattributeClassAttribute:ClassAttributesareuniquetoeachclass.Eachinstanceoftheclasswillhavethisattribute. Python3#declareaclassclassEmployee: #classattribute count=0 #defineamethod defincrease(self): Employee.count+=1 #createanEmployee#classobjecta1=Employee() #callingobject'smethoda1.increase() #printvalueofclassattributeprint(a1.count) a2=Employee() a2.increase() print(a2.count) print(Employee.count)Output:1 2 2Intheaboveexample,thecountvariableisaclassattribute.Pythonproperty():Returnsobjectofthepropertyclass Python3#createaclassclassgfg: #constructor def__init__(self,value): self._value=value #gettingthevalues defgetter(self): print('Gettingvalue') returnself._value #settingthevalues defsetter(self,value): print('Settingvalueto'+value) self._value=value #deletingthevalues defdeleter(self): print('Deletingvalue') delself._value #createaproperties value=property(getter,setter,deleter,) #createagfgclassobjectx=gfg('HappyCoding!')print(x.value) x.value='HeyCoder!' #deletingthevaluedelx.valueOutput:Gettingvalue HappyCoding! SettingvaluetoHeyCoder! DeletingvalueApplicationsByusingproperty()method,wecanmodifyourclassandimplementthevalueconstraintwithoutanychangerequiredtotheclientcode.Sothattheimplementationisbackwardcompatible.MyPersonalNotes arrow_drop_upSave LikePreviousPythonPropertyDecorator-@propertyNext GetterandSetterinPythonRecommendedArticlesPage:10,Mar2027,Apr2001,Sep2004,Dec1927,Apr2005,May2002,Jun2004,May1615,May1610,May1722,Jun1710,Jan1803,Apr1910,Jan1828,Oct1722,Nov1724,Nov1725,Nov1725,Nov1730,Nov1712,Dec1713,Dec1713,Dec1723,Dec17ArticleContributedBy:shubhamtyagi4@shubhamtyagi4VotefordifficultyCurrentdifficulty: ExpertEasy Normal Medium Hard ExpertImprovedBy:shubham_singhkumar_satyamArticleTags:Python-FunctionsPythonReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinPythonReadafilelinebylineinPythonEnumerate()inPythonPythonString|replace()IterateoveralistinPythonHowtoInstallPIPonWindows?MorerelatedarticlesinPythonPythonprogramtoconvertalisttostringDifferentwaystocreatePandasDataframeConvertintegertostringinPythonPrintlistsinPython(4DifferentWays)CreateaPandasDataFramefromLists× Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register
延伸文章資訊
- 1Python property() Method - TutorialsTeacher
- 2Python @property: How to Use it and Why? - Programiz
The @property Decorator. In Python, property() is a built-in function that creates and returns a ...
- 3Built-in Functions — Python 3.10.3 documentation
dict()
- 4Python property() - Programiz
property() returns the property attribute from the given getter, setter, and deleter. If no argum...
- 5property() 函式
事實上在Python中,你可以直接使用property()函式來修改Ball類別。例如: class Ball: def __init__(self, radius): if radius <=...