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></type>
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!

TomergelistsinPython,youcanusethe operator,extendmethod,listcomprehension,oritertools.chain,eachwithspecificadvantages:1)The operatorissimplebutlessefficientforlargelists;2)extendismemory-efficientbutmodifiestheoriginallist;3)listcomprehensionoffersf

In Python 3, two lists can be connected through a variety of methods: 1) Use operator, which is suitable for small lists, but is inefficient for large lists; 2) Use extend method, which is suitable for large lists, with high memory efficiency, but will modify the original list; 3) Use * operator, which is suitable for merging multiple lists, without modifying the original list; 4) Use itertools.chain, which is suitable for large data sets, with high memory efficiency.

Using the join() method is the most efficient way to connect strings from lists in Python. 1) Use the join() method to be efficient and easy to read. 2) The cycle uses operators inefficiently for large lists. 3) The combination of list comprehension and join() is suitable for scenarios that require conversion. 4) The reduce() method is suitable for other types of reductions, but is inefficient for string concatenation. The complete sentence ends.

PythonexecutionistheprocessoftransformingPythoncodeintoexecutableinstructions.1)Theinterpreterreadsthecode,convertingitintobytecode,whichthePythonVirtualMachine(PVM)executes.2)TheGlobalInterpreterLock(GIL)managesthreadexecution,potentiallylimitingmul

Key features of Python include: 1. The syntax is concise and easy to understand, suitable for beginners; 2. Dynamic type system, improving development speed; 3. Rich standard library, supporting multiple tasks; 4. Strong community and ecosystem, providing extensive support; 5. Interpretation, suitable for scripting and rapid prototyping; 6. Multi-paradigm support, suitable for various programming styles.

Python is an interpreted language, but it also includes the compilation process. 1) Python code is first compiled into bytecode. 2) Bytecode is interpreted and executed by Python virtual machine. 3) This hybrid mechanism makes Python both flexible and efficient, but not as fast as a fully compiled language.

Useaforloopwheniteratingoverasequenceorforaspecificnumberoftimes;useawhileloopwhencontinuinguntilaconditionismet.Forloopsareidealforknownsequences,whilewhileloopssuitsituationswithundeterminediterations.

Pythonloopscanleadtoerrorslikeinfiniteloops,modifyinglistsduringiteration,off-by-oneerrors,zero-indexingissues,andnestedloopinefficiencies.Toavoidthese:1)Use'i


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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
