Python property() Method - TutorialsTeacher
文章推薦指數: 80 %
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
延伸文章資訊
- 1[Python教學]@property是什麼? 使用場景和用法介紹
·什麼是只能讀取的屬性? 首先我們先將class 實例化andy = Bank_acount(),當我們print(andy.password) 時,可以獲得密碼:123,當 ...
- 2How to make a class property? [duplicate] - python - Stack ...
Here's how I would do this: class ClassPropertyDescriptor(object): def __init__(self, fget, fset=...
- 3Python Property
The Python property class ... The property() has the following parameters: ... The following uses...
- 4How to make a class property? [duplicate] - Stack Overflow
In python I can add a method to a class with the @classmethod decorator. Is there a similar decor...
- 5Python @property: How to Use it and Why? - Programiz
Class Without Getters and Setters