A decorator is a tool that modifies or enhances the behavior of a function or class without changing its source code. It implements function extension by accepting the objective function or class as parameters and returning a new wrapped function or class. It is often used to add logs, permission control, timing and other functions. To create a decorator: 1. Define a function that receives a function or class; 2. Define a wrapper function in it to add additional operations; 3. Call the original function or class; 4. Return the wrapped result. Just use the @decorator_name syntax to apply it to the objective function or class. For functions with parameters, compatibility can be ensured using *args and **kwargs in the decorator. Python has built-in commonly used decorators such as @staticmethod, @classmethod and @property. Third-party libraries such as Flask also widely use decorators for routing mapping. Decorators are suitable for scenarios where general logic is required to separate core business, but excessive stacking of complex decorators should be avoided to avoid affecting readability and maintenance.
Decorators in Python are a way to modify or enhance functions or classes without changing their source code. They're commonly used to add functionality like logging, access control, timing, and more — all while keeping your code clean and reusable.
What Exactly Is a Decorator?
At its core, a decorator is just a function (or class) that wraps another function or class, modifying its behavior. The key idea is that you pass a function into another function, and the decorator returns a new function that usually does something extra before or after calling the original one.
Here's a basic example:
def my_decorator(func): def wrapper(): print("Before function call") func() print("After function call") Return wrapper @my_decorator def says_hello(): print("Hello") say_hello()
This will output:
Before function call Hello After function call
So when you use @my_decorator
above say_hello
, it's equivalent to writing:
say_hello = my_decorator(say_hello)
How to Create and Use Function Decorators
Creating your own decorator starts with understanding how functions can be passed around as objects. Here's how to build a simple one:
- Define a function that takes another function as an argument.
- Inside it, define a wrapper function that does something extra.
- Call the original function inside the wrapper.
- Return the wrapper function.
You can then apply this decorator using the @decorator_name
syntax right above the function definition.
If your decorated function needs arguments, make sure your wrapper handles them. You can use *args
and **kwargs
for flexibility:
def my_decorator(func): def wrapper(*args, **kwargs): print("Something before") result = func(*args, **kwargs) print("Something after") return result Return wrapper
This version works with any function, regardless of what parameters it accepts.
Using Built-in and Third-Party Decorators
Python comes with some handy decorators built in. For example:
-
@staticmethod
and@classmethod
– Used in classes to define methods that don't require instance or class instance respectively. -
@property
– Makes a method behave like an attribute, useful for computed properties and encapsulation.
Third-party libraries also use decorators heavily. For instance, Flask uses them to map URLs to functions:
@app.route('/') def home(): return "Welcome!"
These tools help reduce boilerplate and make your intentions clear without cluttering logic.
When Should You Use Decorators?
Use decorators when you want to separate cross-cutting concerns from your main logic — things like authentication, logging, caching, input validation, etc.
They're especially useful when:
- You need to apply the same behavior to multiple functions.
- You want to keep your core logic clean and readable.
- You're working on frameworks or libraries where extension matters.
Just remember: a decorator should ideally do one thing well. If you find yourself stacking many complex decorators, consider refactoring or adding comments so others (or future you) can understand what's going on.
That's basically it. They might seem a bit confusing at first, but once you get the pattern down, they become a powerful part of your Python toolkit.
The above is the detailed content of What are decorators in Python, and how do I use them?. 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)

Hot Topics

Polymorphism is a core concept in Python object-oriented programming, referring to "one interface, multiple implementations", allowing for unified processing of different types of objects. 1. Polymorphism is implemented through method rewriting. Subclasses can redefine parent class methods. For example, the spoke() method of Animal class has different implementations in Dog and Cat subclasses. 2. The practical uses of polymorphism include simplifying the code structure and enhancing scalability, such as calling the draw() method uniformly in the graphical drawing program, or handling the common behavior of different characters in game development. 3. Python implementation polymorphism needs to satisfy: the parent class defines a method, and the child class overrides the method, but does not require inheritance of the same parent class. As long as the object implements the same method, this is called the "duck type". 4. Things to note include the maintenance

Parameters are placeholders when defining a function, while arguments are specific values ??passed in when calling. 1. Position parameters need to be passed in order, and incorrect order will lead to errors in the result; 2. Keyword parameters are specified by parameter names, which can change the order and improve readability; 3. Default parameter values ??are assigned when defined to avoid duplicate code, but variable objects should be avoided as default values; 4. args and *kwargs can handle uncertain number of parameters and are suitable for general interfaces or decorators, but should be used with caution to maintain readability.

Iterators are objects that implement __iter__() and __next__() methods. The generator is a simplified version of iterators, which automatically implement these methods through the yield keyword. 1. The iterator returns an element every time he calls next() and throws a StopIteration exception when there are no more elements. 2. The generator uses function definition to generate data on demand, saving memory and supporting infinite sequences. 3. Use iterators when processing existing sets, use a generator when dynamically generating big data or lazy evaluation, such as loading line by line when reading large files. Note: Iterable objects such as lists are not iterators. They need to be recreated after the iterator reaches its end, and the generator can only traverse it once.

A class method is a method defined in Python through the @classmethod decorator. Its first parameter is the class itself (cls), which is used to access or modify the class state. It can be called through a class or instance, which affects the entire class rather than a specific instance; for example, in the Person class, the show_count() method counts the number of objects created; when defining a class method, you need to use the @classmethod decorator and name the first parameter cls, such as the change_var(new_value) method to modify class variables; the class method is different from the instance method (self parameter) and static method (no automatic parameters), and is suitable for factory methods, alternative constructors, and management of class variables. Common uses include:

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

Python's magicmethods (or dunder methods) are special methods used to define the behavior of objects, which start and end with a double underscore. 1. They enable objects to respond to built-in operations, such as addition, comparison, string representation, etc.; 2. Common use cases include object initialization and representation (__init__, __repr__, __str__), arithmetic operations (__add__, __sub__, __mul__) and comparison operations (__eq__, ___lt__); 3. When using it, make sure that their behavior meets expectations. For example, __repr__ should return expressions of refactorable objects, and arithmetic methods should return new instances; 4. Overuse or confusing things should be avoided.

Pythonmanagesmemoryautomaticallyusingreferencecountingandagarbagecollector.Referencecountingtrackshowmanyvariablesrefertoanobject,andwhenthecountreacheszero,thememoryisfreed.However,itcannothandlecircularreferences,wheretwoobjectsrefertoeachotherbuta

Python's garbage collection mechanism automatically manages memory through reference counting and periodic garbage collection. Its core method is reference counting, which immediately releases memory when the number of references of an object is zero; but it cannot handle circular references, so a garbage collection module (gc) is introduced to detect and clean the loop. Garbage collection is usually triggered when the reference count decreases during program operation, the allocation and release difference exceeds the threshold, or when gc.collect() is called manually. Users can turn off automatic recycling through gc.disable(), manually execute gc.collect(), and adjust thresholds to achieve control through gc.set_threshold(). Not all objects participate in loop recycling. If objects that do not contain references are processed by reference counting, it is built-in
