Python property() Method - TutorialsTeacher

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

The property() function is used to define properties in the Python class. The property() method in Python provides an interface to instance attributes. C# ASP.NETCore MVC IoC TypeScript Angular Python SQLServer MongoDB More ✕ .NETTutorials C# ASP.NETCore ASP.NETMVC IoC webapi LINQ ClientSide JavaScript jQuery Node.js D3.js TypeScript Angular11 AngularJS1 Sass ServerSide https Python SQL SQLServer PostgreSQL MongoDB SkillTests ASP.NETCore ASP.NETMVC LINQ C# webapi IoC TypeScript AngularJS Node.js jQuery JavaScript Articles Tests PythonTutorials PythonBuilt-inMethods abs() all() any() ascii() bin() bool() bytearray() bytes() callable() chr() classmethod() complex() delattr() dict() dir() divmod() enumerate() exec() filter() float() getattr() hex() hash() hasattr() help() id() import() int() input() isinstance() issubclass() iter() len() list() map() max() memoryview() min() next() object() oct() open() ord() pow() print() property() range() repr() reversed() round() set() setattr() slice() sorted() str() sum() super() tuple() type() vars() zip() PythonStringMethods PythonListMethods PythonSetMethods PythonDictionaryMethods Python-property()function Theproperty()functionisusedtodefinepropertiesinthePythonclass. Theproperty()methodinPythonprovidesaninterfacetoinstanceattributes. Itencapsulatesinstanceattributesandprovidesaproperty,sameasJavaandC#. Theproperty()methodtakestheget,setanddeletemethodsasargumentsandreturnsanobjectofthepropertyclass. Itisrecommendedtousethepropertydecoratorinsteadoftheproperty()method. property(fget,fset,fdel,doc) Parameters: fget:(Optional)Functionforgettingtheattributevalue.Defaultvalueisnone. fset:(Optional)Functionforsettingtheattributevalue.Defaultvalueisnone. fdel:(Optional)Functionfordeletingtheattributevalue.Defaultvalueisnone. doc:(Optional)Astringthatcontainsthedocumentation.Defaultvalueisnone. ReturnValue: Returnsthepropertyattributefromthegivengetter,setter,anddeleter. ThefollowingexampledemonstrateshowtocreateapropertyinPythonusingtheproperty()function. Example:property()Copy classperson: def__init__(self): self.__name='' defsetname(self,name): print('setname()called') self.__name=name defgetname(self): print('getname()called') returnself.__name name=property(getname,setname) Intheaboveexample,property(getname,setname)returnsthepropertyobjectandassignsittoname. Thus,thenamepropertyhidestheprivateinstanceattribute__name. Thenamepropertyisaccesseddirectly,butinternallyitwillinvokethegetname()orsetname()method,asshownbelow. Example:property()Copy >>>frompersonimportperson >>>p1=person() >>>p1.name="Steve" setname()called >>>p1.name getname()called 'Steve' Asyoucanseeabove,thegetname()methodgetscalledautomaticallywhenweaccessthenameproperty. Inthesameway,thesetnamemethodgetscalledwhenweassignavaluetothenameproperty. Italsohidestheinstanceattribute__name. Inthesameway,youcanspecifyadeletermethodfortheproperty,asshowninthebelowscript. Example:property()Copy classperson: def__init__(self,name): self.__name=name defsetname(self,name): print('setname()called') self.__name=name defgetname(self): print('getname()called') returnself.__name defdelname(self): print('delname()called') delself.__name #Setpropertytouseget_name,set_name #anddel_namemethods name=property(getname,setname,delname) Thedelname()functionwouldbeinvokedwhenyoudeletethenameproperty. Example:property()Copy >>>frompersonimportperson >>>p1=person() >>>p1.name="Steve" setname()called >>>delp1.name delname()called Inthisway,wecandefineapropertyintheclassusingtheproperty()functioninPython. @propertydecoratormakesiteasytodeclareapropertyinsteadofcallingtheproperty()function.Learnaboutitnext. Share Tweet Share Whatsapp WanttocheckhowmuchyouknowPython? StartPythonTest



請為這篇文章評分?