


Tricky usage of @property decorator in Python (code example)
This article brings you the technical usage (code examples) of the @property decorator in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
@property decorator can turn a method into a property and call it. Let’s take a look at Python’s black magic @property decorator usage skills analysis
@ What are attributes used for? On the surface, it seems that a method is accessed as an attribute.
The above code
class Circle(object): def __init__(self, radius): self.radius = radius @property def area(self): return 3.14 * self.radius ** 2 c = Circle(4) print c.radius print c.area
As you can see, although the area is defined in the form of a method, after adding @property, it can be accessed directly c.area as a property.
Now the question comes. Every time c.area is called, it will be calculated once. It is a waste of CPU. How can it be calculated only once? This is the property of laziness.
class lazy(object): def __init__(self, func): self.func = func def __get__(self, instance, cls): val = self.func(instance) setattr(instance, self.func.__name__, val) return val class Circle(object): def __init__(self, radius): self.radius = radius @lazy def area(self): print 'evalute' return 3.14 * self.radius ** 2 c = Circle(4) print c.radius print c.area print c.area print c.area
As you can see, 'evalute' is only output once, so you should have a good understanding of @Lazy's mechanism.
Here, the lazy class has a __get__ method, which indicates that it is a descriptor. When c.area is executed for the first time, due to order issues, it is first searched in Ç.__dict__. If it is not found, just Go to the class space to find it. In the class circle, there is the area() method, so it is intercepted by __get__.
In __get__, call the region() method of the instance to calculate the result, and dynamically add an attribute with the same name to the instance and assign the result to it, that is, add it to Ç.__ dict__.
When executing c.area again, first go to Ç.__ dict__ to find it, because it is already there at this time, so it will not go through the area () method and __get__.
Attention
Please pay attention to the following code scenarios:
Code snippet 1:
class Parrot(object): def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage if __name__ == "__main__": # instance p = Parrot() # similarly invoke "getter" via @property print p.voltage # update, similarly invoke "setter" p.voltage = 12
Code snippet 2:
class Parrot: def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage if __name__ == "__main__": # instance p = Parrot() # similarly invoke "getter" via @property print p.voltage # update, similarly invoke "setter" p.voltage = 12
Code 1 ,The difference between 2 is
class Parrot (object):
Under python2, run the test separately
Fragment 1: An expected error message AttributeError: Unable to be prompted Set properties
Fragment 2: Correct operation
Refer to the python2 documentation. @property will provide a ready-only attribute. The above code does not provide the corresponding @voltage.setter. It stands to reason that the code in Fragment 2 will Prompt running error, in the python2 documentation, we can find the following information:
BIF:
property([fget[,fset[,fdel[,doc]]]])
Returns the attribute properties of the new style class (classes derived from Object).
It turns out that under python2, the built-in type object is not the default base class. If there is no clear explanation when defining the class (code snippet 2), the Parrot we defined (code snippet 2) will not inherit Object
The object class just provides the @property function we need. We can find the following information in the document:
New style lesson
Any class that inherits from object . This includes all built-in types such as list and dict. Only new-style classes can use Python's newer, generic features such as __slots__, descriptors, attributes and __getattribute__().
At the same time, we can also verify through the following method
class A: pass >>type(A) <type 'classobj'>
class A(object): pass >>type(A) <type 'type'>
From the returned
In order to consider the compatibility of the python version of the code during the transition period Question, I think when defining a class file, you should explicitly define the object as a good habit
The final code will be as follows:
class Parrot(object): def __init__(self): self._voltage = 100000 @property def voltage(self): """Get the current voltage.""" return self._voltage @voltage.setter def voltage(self, new_value): self._voltage = new_value if __name__ == "__main__": # instance p = Parrot() # similarly invoke "getter" via @property print p.voltage # update, similarly invoke "setter" p.voltage = 12
The above is the detailed content of Tricky usage of @property decorator in Python (code example). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

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

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

Undress AI Tool
Undress images for free

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)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
