Skip to content

Commit 2bcc852

Browse files
authored
Merge pull request #1095 from AmrutaJayanti/Dec
Create Decorators-Lambda-Functions.md
2 parents f13ac94 + 3a232dd commit 2bcc852

File tree

1 file changed

+149
-0
lines changed

1 file changed

+149
-0
lines changed
Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
# Decorators
2+
3+
Decorators in Python are a powerful and flexible feature that allows you to modify or enhance the behavior of functions or classes. They are essentially functions that wrap other functions or methods, allowing you to add functionality before, after, or around the original function's behavior.
4+
5+
#### Syntax
6+
7+
Decorators use the `@decorator_name` syntax above the function definition.
8+
9+
### Types of Decorators
10+
11+
**1. Built-in Function Decorators**
12+
13+
- `@staticmethod`: Defines a method that does not operate on an instance of the class or modify its state.
14+
- `@classmethod`: Defines a method that operates on the class itself, rather than an instance.
15+
- `@property`: Allows you to define methods in a class that can be accessed like attributes.
16+
17+
```python
18+
class MyClass:
19+
def __init__(self, value):
20+
self._value = value
21+
22+
@property
23+
def value(self):
24+
return self._value
25+
26+
@value.setter
27+
def value(self, new_value):
28+
self._value = new_value
29+
30+
@staticmethod
31+
def static_method():
32+
print("This is a static method.")
33+
34+
@classmethod
35+
def class_method(cls):
36+
print("This is a class method.")
37+
```
38+
39+
**2. Custom Function Decorators:**
40+
41+
- Simple Function Decorators : Adds functionality to a function.
42+
```python
43+
def my_decorator(func):
44+
def wrapper():
45+
print("Something is happening before the function is called.")
46+
func()
47+
print("Something is happening after the function is called.")
48+
return wrapper
49+
50+
@my_decorator
51+
def say_hello():
52+
print("Hello!")
53+
54+
say_hello()
55+
```
56+
- Decorator with Arguments: Takes arguments to modify the behavior.
57+
```python
58+
def repeat(num_times):
59+
def decorator_repeat(func):
60+
def wrapper(*args, **kwargs):
61+
for _ in range(num_times):
62+
result = func(*args, **kwargs)
63+
return result
64+
return wrapper
65+
return decorator_repeat
66+
67+
@repeat(num_times=3)
68+
def greet(name):
69+
print(f"Hello {name}")
70+
71+
greet("Alice")
72+
```
73+
Here, `*args` and `**kwargs` are special syntax in Python that allow a function to accept an arbitrary number of positional and keyword arguments.
74+
75+
**3. Class Decorators:**
76+
77+
Instead of taking functions as the decorators , here we use the class definition as the decorator.
78+
79+
```python
80+
def class_decorator(cls):
81+
class Wrapped(cls):
82+
def new_method(self):
83+
return "New Method"
84+
return Wrapped
85+
86+
@class_decorator
87+
class MyClass:
88+
def original_method(self):
89+
return "Original Method"
90+
91+
instance = MyClass()
92+
print(instance.original_method())
93+
print(instance.new_method())
94+
```
95+
96+
### Decorators Chaining
97+
98+
You can apply multiple decorators to a single function. Decorators are applied from bottom to top.
99+
100+
```python
101+
def decorator1(func):
102+
def wrapper():
103+
print("Decorator 1")
104+
func()
105+
return wrapper
106+
107+
def decorator2(func):
108+
def wrapper():
109+
print("Decorator 2")
110+
func()
111+
return wrapper
112+
113+
@decorator1
114+
@decorator2
115+
def my_function():
116+
print("Hello!")
117+
118+
my_function()
119+
```
120+
121+
122+
# Lambda Functions
123+
124+
Lambda functions in Python, also known as anonymous functions, are small, unnamed functions defined using the `lambda` keyword.
125+
126+
#### Syntax
127+
128+
```python
129+
lambda arguments: expression
130+
```
131+
132+
#### Example:
133+
134+
```python
135+
from functools import reduce
136+
137+
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
138+
139+
# Filter even numbers, square them, and then find their product
140+
even_squares_product = reduce(
141+
lambda x, y: x * y,
142+
map(lambda x: x**2, filter(lambda x: x % 2 == 0, numbers))
143+
)
144+
145+
print(even_squares_product) # Output: 64 * 16 * 36 * 100 = 3686400
146+
```
147+
148+
149+

0 commit comments

Comments
 (0)