Minor Project
Minor Project
Defining a Decorator:
A decorator is a function that accepts an argument (usually another
function).
Within the decorator function you can define a wrapper function
which performs before or after the original function.
Built-in Decorators
Python has some built-in decorators like:
@staticmethod : A method which does not read any of the class's
properties.
@classmethod : Specifies a method that takes a class instead of an
instance as its first argument.
@property : Declare a method as a class property.
Important Considerations
Decorators can be a bit challenging to debug since they
overwrite the original function. Use functools.wraps to store the
original function’s metadata.
Example:
Now as you can see, Here I have created a simple program using
DECORATOR. In this program I have used “intro” as a wrapper and
greeting as a function.
When we will run this program, as a output first we will get “Hi,
my self N “. Then it will print “I am a python developer” and then it
will print “What’s your name…? “ , then it will take name as a input
from user and will store name in variable a and at the end it will print
“It’s nice to meet you ‘input_name’”.
Using Generators:
You can loop through a generator or use functions like next() to get
values one at a time.
Benefits of Generators:
Memory Efficiency: Generators do not hold the entire sequence in
memory. They produce each value as needed.
Lazy Evaluation: Values are generated only when requested, which
can enhance performance, especially with large datasets.
Use:
Generators are ideal for reading large files line by line, creating
infinite sequences, or streaming data.
Example:
Here I have defined a simple generator. In this generator I have
taken three values.
Then I have stored this generator in variable “gen”.
Then when we use next(gen), compiler will print first Initial value,
Then again when we will use next(gen), compiler will print Middle
value, and third time it will print Last value.
Conclusion:
Python decorator and generator can be used in various way in python
programming, and they are easy to study and apply.