python property decorator example
@property decorator is used to convert methods into properties to implement the reading, setting and deletion control of properties. 1. Basic usage: define read-only attributes through @property, such as area calculated based on radius and accessed directly; 2. Advanced usage: use @name.setter and @name.deleter to implement attribute assignment verification and deletion operations; 3. Practical application: perform data verification in setters, such as BankAccount to ensure that the balance is not negative; 4. Naming specification: internal variables are prefixed, the property method name is consistent with the attribute, and unified access control is used to improve code security and maintainability.
In Python, the @property
decorator is used to convert a method into a property, so that you can call it like you access a property without using parentheses. This method allows you to control the reading, setting and deletion of properties without changing the interface, and is often used for encapsulation and data verification.

Here is a simple example of @property
usage:
✅ Basic usage: Change method to read-only attribute
class Circle: def __init__(self, radius): self._radius = radius @property def area(self): return 3.14159 * self._radius ** 2 # Use example c = Circle(5) print(c.area) # Output: 78.53975 # c.area = 10 # Error: Cannot assign value (read-only attribute)
Here
area
looks like an attribute, but is actually calculated. The user does not need to callc.area()
, justc.area
.
✅ Advanced usage: Supports reading, setting, and deletion (getter, setter, delete)
class Person: def __init__(self, name): self._name = name @property def name(self): print("Getting name...") return self._name @name.setter def name(self, value): if not value: raise ValueError("Name cannot be empty") print(f"Setting name to {value}") self._name = value @name.deleter def name(self): print("Deleting name...") del self._name # Use example p = Person("Alice") print(p.name) # Output: Getting name... \n Alice p.name = "Bob" # Output: Setting name to Bob print(p.name) # Output: Getting name... \n Bob del p.name # Output: Deleting name... # print(p.name) # Error: name has been deleted
✅ Practical application scenario: Data verification encapsulation
class BankAccount: def __init__(self, balance): self._balance = 0 self.balance = balance # Initialize @property with setter def balance(self): return self._balance @balance.setter def balance(self, amount): if amount < 0: raise ValueError("Balance cannot be negative") self._balance = amount # Use example acc = BankAccount(100) print(acc.balance) # 100 acc.balance = 200 print(acc.balance) # 200 # acc.balance = -50 # Throw ValueError
✅ Tips: Naming Specifications
- Usually, use the
_
to represent "protected" internal variables (such as_name
,_balance
) -
@property
method name is the same as the property name (such asname
) - Avoid direct manipulation of internal variables and always access through property control
Basically that's it. @property
makes the code cleaner and safer, and is a very practical tool in object-oriented programming in Python.
The above is the detailed content of python property decorator example. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)
![You are not currently using a display attached to an NVIDIA GPU [Fixed]](https://img.php.cn/upload/article/001/431/639/175553352135306.jpg?x-oss-process=image/resize,m_fill,h_207,w_330)
Ifyousee"YouarenotusingadisplayattachedtoanNVIDIAGPU,"ensureyourmonitorisconnectedtotheNVIDIAGPUport,configuredisplaysettingsinNVIDIAControlPanel,updatedriversusingDDUandcleaninstall,andsettheprimaryGPUtodiscreteinBIOS/UEFI.Restartaftereach

The Java design pattern is a reusable solution to common software design problems. 1. The Singleton mode ensures that there is only one instance of a class, which is suitable for database connection pooling or configuration management; 2. The Factory mode decouples object creation, and objects such as payment methods are generated through factory classes; 3. The Observer mode automatically notifies dependent objects, suitable for event-driven systems such as weather updates; 4. The dynamic switching algorithm of Strategy mode such as sorting strategies improves code flexibility. These patterns improve code maintainability and scalability but should avoid overuse.

AdeadlockinJavaoccurswhentwoormorethreadsareblockedforever,eachwaitingforaresourceheldbytheother,typicallyduetocircularwaitcausedbyinconsistentlockordering;thiscanbepreventedbybreakingoneofthefournecessaryconditions—mutualexclusion,holdandwait,nopree

UseOptional.empty(),Optional.of(),andOptional.ofNullable()tocreateOptionalinstancesdependingonwhetherthevalueisabsent,non-null,orpossiblynull.2.CheckforvaluessafelyusingisPresent()orpreferablyifPresent()toavoiddirectnullchecks.3.Providedefaultswithor

TheOilPaintfilterinPhotoshopisgreyedoutusuallybecauseofincompatibledocumentmodeorlayertype;ensureyou'reusingPhotoshopCS6orlaterinthefulldesktopversion,confirmtheimageisin8-bitperchannelandRGBcolormodebycheckingImage>Mode,andmakesureapixel-basedlay

Micronautisidealforbuildingcloud-nativeJavaapplicationsduetoitslowmemoryfootprint,faststartuptimes,andcompile-timedependencyinjection,makingitsuperiortotraditionalframeworkslikeSpringBootformicroservices,containers,andserverlessenvironments.1.Microna

RuntheapplicationorcommandasAdministratorbyright-clickingandselecting"Runasadministrator"toensureelevatedprivilegesaregranted.2.CheckUserAccountControl(UAC)settingsbysearchingforUACintheStartmenuandsettingtheslidertothedefaultlevel(secondfr

Understand JCA core components such as MessageDigest, Cipher, KeyGenerator, SecureRandom, Signature, KeyStore, etc., which implement algorithms through the provider mechanism; 2. Use strong algorithms and parameters such as SHA-256/SHA-512, AES (256-bit key, GCM mode), RSA (2048-bit or above) and SecureRandom; 3. Avoid hard-coded keys, use KeyStore to manage keys, and generate keys through securely derived passwords such as PBKDF2; 4. Disable ECB mode, adopt authentication encryption modes such as GCM, use unique random IVs for each encryption, and clear sensitive ones in time
