Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
10 views5 pages

What Is Decorator With Example

The document provides an overview of various Python programming concepts including decorators, iterators, generators, list comprehensions, lambda functions, and more. It explains their definitions, uses, and provides examples for clarity. Additionally, it covers topics such as recursion, constructors, destructors, abstraction, magic methods, regular expressions, debugging, and coding standards.

Uploaded by

annamarriage15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views5 pages

What Is Decorator With Example

The document provides an overview of various Python programming concepts including decorators, iterators, generators, list comprehensions, lambda functions, and more. It explains their definitions, uses, and provides examples for clarity. Additionally, it covers topics such as recursion, constructors, destructors, abstraction, magic methods, regular expressions, debugging, and coding standards.

Uploaded by

annamarriage15
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

1. What is decorator with example?

Ans: Decorator is function that can add additional functionality to an existing function.
Ex:- def decorator(func):
def addon(a, b):
print('i am going to sum by',a,'and',b)
if a>b:
print("Whoops! cannot sum")
return
return func(a, b)
return addon

@decorator
def sum(a,b):
return a+b
sum(10,15)
2. Iterator in python?
Ans: An iterator is an objects that contain countable numbers of values. in Python
implements the iterator protocol, which consist of the methods __iter__() and __next__().
EX:-
x = ("apple", 1234, 2.0)
y = iter(x)

print(next(y))
print(next(y))
print(next(y))
3. Iterator vs iterable?
Ans: Lists, tuples, dictionaries, and sets are all iterable objects. They are
iterable containers which you can get an iterator from.
4. Generators
Generator is a function that return an object which we can iterate one value at a time.
Instead of return yield keyword is used to make a function as generator function.

Generator are useful when we want to produce a large number of sequence of values, but
we don’t want all of them in memory at once.

def my_func(x):
for I in range(x):
yield i*i
res=my_func(5)
print(next(res))
5. what is the use of list comprehension in python?
List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.
Ex:-1
X= [‘hari’, ‘krishna’, ‘gangavarapu’]
newlist=[i for i in x if ‘a’ in i]
print(newlist)
6. lambda function
A lambda function is a small anonymous function it does not have a name. Lambda function
take any number of arguments but can have one expression.
X= lambda n: n*n
Print(X(5))
7. filter function in lambda?
The filter function is a python built in function. That applies a given function to each item of
an iterable return only a list of filtered True condition results.
Syntax: Filter(function, sequence)
Ex:- Finding the even numbers
a = [45,5,6,7,8,9,4,2]
res = list(filter(lambda x: x%2==0, a))
print(res)
8. Map function in lambda?
The filter function is a python built in function. That applies a given function to each item of
an iterable return a list of results with based on function logic.
Syntax: map(function, sequence)
Ex:- square of the number
a = [1,2,3,4,5]
res = list(map(lambda x: x*x, a)
print(res)
9. Reduce function in lambda?
The filter function is a python built in function. That applies a given function to each item of
an iterable and return a single value.
Syntax: reduce(function, sequence)
From functools import reduce
Ex:- find the sum of list
a = [1,2,34,5,6,7]
res = reduce(lambda x, y: x + y, a)
print(res)
10. What is the use of enumerate function?
enumerate() allows us to iterate through a sequence but it keeps track of both the index and
the element. The enumerate() function takes in an iterable as an argument, such as a list,
string, tuple, or dictionary.
Ex:-
l= [1,2,3,4,56,5]
for i , j in enumerate(l):
print(i, j)
11. Recursion
Recursion is the process of defining something in terms of itself.
Ex:- def factorial(x):

if x == 0:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
12. Constructor
The __init__ method is constructor in python. Constructors are used to initialize the
object’s state.
default constructor: The default constructor is a simple constructor which doesn’t have any
argument to pass. Its definition has only one argument which is a reference to the instance
being constructed.
Parameterized constructor: constructor which has parameters to pass is known as
parameterized constructor. The parameterized constructor takes its first argument as a
reference to the instance being constructed known as self.
Class A(object):
def __init__(self):
self.str1 = ‘prepinsta’
print(self.str1)
print(‘in constructor’)
ob = A()
13. Destructor
The __del__ method is similar to destructor in python. Destructors are used to destroying
the object’s state.
class A(object):
def __init__(self):
self.str1 = ‘PrepInsta’
print('Object Created' , self.str1)
def __del__(self):
print('DEstructor is called Manually')
ob = A()
del ob
14. What is abstraction in python?
Abstraction is the mechanism of only declaring methods but not instantiated, declared
methods are implemented in its sub classes.
15. Magic method and uses in python?
Magic methods in python are special methods that start and ends with the double
underscores.
Ex:- when you add two numbers using the + operator, internally the __add__ method will be
called.
16. Split in regular expression?
This function splits the string according to the occurrences of a character
import re
from re import split

print(split('\W+', 'Words, words , Words'))


print(split('\W+', "Word's words Words"))
print(split('\W+', 'On 12th Jan 2016, at 11:02 AM'))
print(split('\d+', 'On 12th Jan 2016, at 11:02 AM'))

sub in regular Expression?


Find all substrings where the RE matches and replace them with a different string.
import re
print(re.sub('ub', '~*' , 'Subject has Uber booked already', flags = re.IGNORECASE))
print(re.sub('ub', '~*' , 'Subject has Uber booked already'))
print(re.sub('ub', '~*' , 'Subject has Uber booked already', count=1, flags = re.IGNORECASE))
print(re.sub(r'\sAND\s', ' & ', 'Baked Beans And Spam', flags=re.IGNORECASE))

Subn in regular expressions?


Subn also same as sub(), but returns the new string and the number of replacements.
import re

print(re.subn('ub', '~*' , 'Subject has Uber booked already'))


t = re.subn('ub', '~*' , 'Subject has Uber booked already', flags = re.IGNORECASE)
print(t)
print(len(t))
print(t[0],t[1])
17. How to get current data and time in python?
From datetime import datetime
day= datetime.now()
current_time = day.strftime(‘%H:%M:%S)
print(current_time)
18. Pass, continue and breaks?
Pass: The pass statement is used as a placeholder for future code.
When the pass statement is executed noting happens but you avoid getting an error when
empty code is not allowed.
Continue: The continue keyword is used to end the current iteration in a for loop continue
the next iteration.
Break: Break statement stops the iteration and terminate the loop.
19. What is the difference between range and xrange?
The range() function return a sequence consisting of number that are immutables. The
xrange() function return a generator object of xrange type. The range function is less
memory optimized. The xrange() function is more memory optimized.
20. What is PYTHONPATH?
Pythonpath is a special environment variable that provides guidance to the Python
interpreter about where to find various libraries and applications.

Add to the PYTHONPATH in windows.


My Computer > Properties > Advanced System Settings > Environment Variables
>New>Variable name> Path.
21. Use of unittesting?
Unit testing is a technique in which particular module is tested to check by developer himself
whether there are any errors. The primary focus of unit testing is test an individual unit of
system to analyze, detect, and fix the errors.
22. Array and list?
Array: An array is a data structure that holds fix number of elements and these elements
should be of the same data type.
List: the list is written as the list of commas separated values inside the square bracket. The
most important advantage of the list is the elements inside the list is not compulsorily be of
the same data type along with negative indexing.
23. Difference between the set and frozen set?
A set is a mutable object while frozenset provides an immutable implementation.
24. How to debugging the python code?
If you're only interested in debugging a Python script, the simplest way is to select the down-
arrow next to the run button on the editor and select Debug Python File in Terminal.
25. What are coding standards in Python?
Coding standards are collections of rules and guidelines that determine the programming
style, procedures, and methods for programming language.
26. Shallow copy and deep copy?
Shallow: In Shallow copy, a copy of the original object is stored and only the reference
address is finally copied.
Deep copy: In Deep copy, the copy of the original object and the repetitive copies both are
stored.
Ex:- shallow copy
Import copy
Old=[[1,2,3],[4,5,6],[7,8,9]]
New=copy.copy(Old)
New[0] = [‘a’,’b’,’c’]
Print(Old)
Print(New)
OUTPUT:
Old: [[1,2,3],[4,5,6],[7,8,9]]
New: [[‘a’,’b’,’c’], [4,5,6],[7,8,9]]

Old=[[1,2,3],[4,5,6],[7,8,9]]
New=copy.copy(Old)
New[0][2] = ‘c’
Print(Old)
Print(New)
OUTPUT:
Old: [[1,2,’c’],[4,5,6],[7,8,9]]
New: [[1,2,’c’], [4,5,6],[7,8,9]]

Deep copy:
Old=[[1,2,3],[4,5,6],[7,8,9]]
New=copy.deepcopy(Old)
New[0][2] = ‘c’
Print(Old)
Print(New)
OUTPUT:
Old: [[1,2,3],[4,5,6],[7,8,9]]
New: [[1,2,’c’], [4,5,6],[7,8,9]]

You might also like