Pages

Monday, March 14, 2016

Custom Implementation of Python Basic Concepts

Iterator

class custom_iterator():
    
    def __init__(self, start, end, interval=None):
        self.start = start
        self.end = end
        self.interval = interval
    
    def __iter__(self):
        return self
    
    def next(self):
        if self.start < self.end:
            if self.interval:
                self.start += self.interval
                return self.start - self.interval
            else:
                self.start += 1
                return self.start - 1
        else:
            raise StopIteration
            
for i in custom_iterator(1, 10):
    print i

"Iterator means to interate value one by one from the sequence. In custom iterator we need to create class which shoud be iterated by __iter__ function so that to implement iter functionality. Here, we can pass two argument with default interval, if we want custom interval also then we will pass three arguments in custom iterator like custom_iterator(1, 10, 2)"

Generator

def custom_generator(start, end, interval=None):
    while start < end:
        yield start
        if interval:
            start += interval
        else:
            start += 1
    else:
        raise StopIteration
        
for j in custom_generator(1, 10, 2):
    print j
    
"Don't forget yield statment whenever we will talk about generator, it used to store currrent status of the function and continue with previous state, this type of function also called co-routing function".
    

Decorator

def first_decorator(func):
    
    def wrapper_function(*args, **kwargs):
       # here can code for extra functionality
        return func(*args, **kwargs)
    
    return wrapper_function

@first_decorator
def add_val(x, y):
    return x + y

print "val", add_val(10, 20)

"Decorator means pass the function as arguments in other function, why we need to do this type of implementation because object oriented concept is write once read many times, to proof this concept without any changes in previos function we will add new funtionality in newly created function".

Exception

class CustomError(Exception):
    def __init__(self, arg):
        # Set some exception infomation
        self.msg = arg

try:
    # Raise an exception with argument
    raise CustomError('This is a CustomError')
except CustomError, arg:
    # Catch the custom exception
    print 'Error: ', arg.msg 

"Custom Eception, where user will create own exception class and based on the condition will raise error message".

Enjoy ... :)

No comments:

Post a Comment