@是Python中用于装饰器的语法糖,可增强函数或类行为而不修改其代码。1. 基本用法:@decorator等价于func = decorator(func),在函数定义前使用可添加前置或后置操作。2. 带参数装饰器:通过三层函数嵌套实现,如@repeat(3)先调用外层函数生成装饰器。3. 类装饰器:可用于控制实例创建,如@singleton确保类仅有一个实例。4. 内置装饰器:@staticmethod定义静态方法,@classmethod定义类方法,@property使方法像属性一样访问,提升封装性与可读性。

在 Python 中,@ 是一个特殊的语法符号,主要用于装饰器(Decorator)。它用来修改或增强函数或类的行为,而不需要改变其内部代码。
1. 装饰器的基本用法
当你在函数或类前面使用 @decorator_name,相当于把该函数或类作为参数传给装饰器函数进行处理。
例如:
def my_decorator(func):def wrapper():
print("函数执行前")
func()
print("函数执行后")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
输出结果为:
立即学习“Python免费学习笔记(深入)”;
函数执行前Hello!
函数执行后
这里 @my_decorator 相当于写成:say_hello = my_decorator(say_hello)
2. 带参数的装饰器
如果装饰器本身需要接收参数,可以再嵌套一层函数:
def repeat(n):def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(n):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def greet():
print("Hi!")
greet()
会打印三次 "Hi!"。这里的 @repeat(3) 先调用 repeat(3),返回真正的装饰器,再应用到函数上。
3. 类装饰器
装饰器也可以用于类,用来修改类的行为或注册类信息。
def singleton(cls):instances = {}
def get_instance(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return get_instance
@singleton
class MyConfig:
pass
这样就实现了单例模式,确保这个类只有一个实例。
4. 内置装饰器示例
Python 提供了一些常用内置装饰器:
- @staticmethod:定义静态方法,不接收 self 或 cls
- @classmethod:定义类方法,第一个参数是 cls
- @property:将方法变成属性访问
例如:
class Circle:def __init__(self, radius):
self._radius = radius
@property
def area(self):
return 3.14 * self._radius ** 2
之后就可以像访问属性一样使用:circle.area,而不需要加括号。
基本上就这些。@ 符号让代码更简洁、可读性更强,是 Python 中非常实用的功能。理解它有助于写出更优雅的代码。











