Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is @ operator in Python?
The @ operator in Python serves multiple purposes. It's primarily used to define decorators, but it also functions as the matrix multiplication operator (introduced in Python 3.5). Let's explore both uses with practical examples.
@ Operator as Decorator
A decorator is a function that takes another function and extends its behavior without explicitly modifying it. The @ symbol provides clean syntax for applying decorators ?
Basic Decorator Example
def my_decorator(func):
def wrapper():
print("Before function call")
func()
print("After function call")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
Before function call Hello! After function call
Decorator with Parameters
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for i in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
Hello, Alice! Hello, Alice! Hello, Alice!
@ Operator for Matrix Multiplication
In Python 3.5+, the @ operator performs matrix multiplication with NumPy arrays ?
import numpy as np
# Create two matrices
matrix_a = np.array([[1, 2], [3, 4]])
matrix_b = np.array([[5, 6], [7, 8]])
# Matrix multiplication using @ operator
result = matrix_a @ matrix_b
print("Matrix A:")
print(matrix_a)
print("\nMatrix B:")
print(matrix_b)
print("\nA @ B =")
print(result)
Matrix A: [[1 2] [3 4]] Matrix B: [[5 6] [7 8]] A @ B = [[19 22] [43 50]]
Types of Decorators
Python supports two main types of decorators ?
- Function decorators − Modify function behavior
- Class decorators − Modify class behavior
Class Decorator Example
def add_method(cls):
def new_method(self):
return f"Added method to {self.__class__.__name__}"
cls.added_method = new_method
return cls
@add_method
class MyClass:
def __init__(self, name):
self.name = name
obj = MyClass("Test")
print(obj.added_method())
Added method to MyClass
Comparison
| Use Case | Syntax | Purpose |
|---|---|---|
| Decorator | @decorator_name |
Modify function/class behavior |
| Matrix Multiplication | A @ B |
Multiply matrices (NumPy) |
Conclusion
The @ operator serves dual purposes in Python: decorators for modifying functions/classes and matrix multiplication for NumPy arrays. Decorators provide clean syntax for extending functionality without modifying the original code.
