PythonPlacement Classroomnotes 14/Mar/2022

Liskovs Substitution Principle

  • This principle States that a child class must be substitutable for its parent class

Duck Typing

  • The term comes from the saying “If it walks like a duck and it quacks like a duck then it must be a duck”
  • Duck typing is related to dynamic typing, where the type or class of an object is less important that the method it defines
import math
class Car:

    def __len__(self):
        return 3985

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def __len__(self):
        return int(2 * math.pi * self.radius)


if __name__ == "__main__":
    name_str = "Learning Python"
    numbers_list = [1,2,3,4,5]
    course_dict = { 'name': 'python', 'duration': 120}
    print(len(name_str))
    print(len(numbers_list))
    print(len(course_dict))
    thar = Car()
    print(len(thar))
    circle = Circle(10)
    print(len(circle))

Sample Problem

  • Exercise: write a function to find sum of all prime numbers in the given range
def is_prime(number):
    for index in range(2, number):
        if number % index == 0:
            return False
    return True


def sum_of_primes(start, stop):
    # using list comprehensions
    primes = [ number for number in range(start, stop+1) if is_prime(number)]
    return sum(primes)

if __name__ == "__main__":
    print(sum_of_primes(5,15))

Factory Pattern

  • This belongs to Creational Pattern
  • Factory pattern is a creational design pattern used to create concret implementations of a common interface
  • It seperates the process of creating an object from code that depends of interface of object

  • Consider the Below Code

import json
import yaml
class Movie:
    def __init__(self, title, starcast, genre, director):
        self.title = title
        self.starcast = starcast
        self.genre = genre
        self.director = director

class MovieSerializer:
    def serialize(self, movie:Movie, format:str):
        movie_info = {
               'title': movie.title,
               'starcast': movie.starcast,
               'genre': movie.genre,
               'director': movie.director
           }
        if format == "JSON":
           return json.dumps(movie_info) 
        elif format == "YAML":
            return yaml.dump(movie_info)
        else:
            return ValueError(format)

if __name__ == "__main__":
    movie = Movie('Avengers', 'Robert Downey jr', 'Scifi', 'xxxxxxxx')
    movie_serialize = MovieSerializer()
    print(movie_serialize.serialize(movie, "JSON"))
  • Managing implementations with conditional loops is not a good idea
  • Try understanding the follow code
import json
from venv import create
import yaml

class SerializerBase:
    def __init__(self) -> None:
        self._current_object = dict()

    def add_property(self, name, value):
        self._current_object[name] = value

    def to_str(self):
        return None

class YamlSerializer(SerializerBase):
    def to_str(self):
        yaml.dump(self._current_object)


class JsonSerializer(SerializerBase):
    def to_str(self):
        json.dumps(self._current_object)



class Movie:
    def __init__(self, title, starcast, genre, director):
        self.title = title
        self.starcast = starcast
        self.genre = genre
        self.director = director

    def serialize(self, serializer:SerializerBase):
        serializer.add_property('title', self.title)
        serializer.add_property('starcast', self.starcast)
        serializer.add_property('genre',self.genre)
        serializer.add_property('director', self.director)
        return serializer.to_str()


class SerializerFactory:
    def __init__(self) -> None:
        self._creators = {}

    def register_format(self, format, creator):
        self._creators[format] = creator
        if not creator:
            raise ValueError(format)

    def get_serializer(self, format):
        creator = self._creators.get(format)
        return creator()


if __name__ == '__main__':
    factory = SerializerFactory()
    factory.register_format('JSON', JsonSerializer)
    factory.register_format('YAML', YamlSerializer)
    movie = Movie('Avengers', 'Robert Downey jr', 'Scifi', 'xxxxxxxx')
    serializer = factory.get_serializer('JSON')
    movie.serialize(serializer)


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About continuous learner

devops & cloud enthusiastic learner