Python Classroom Series – 23/Jun/2021

Composition in Python

  • One Example Around Composition
class Movie:
    def __init__(self, name):
        self.__name = name

    def name(self):
        return self.__name

    def __str__(self) -> str:
        return self.__name

class Ticket:
    def __init__(self, movie=None, location=None):
        if movie is None:
            movie = Movie('Avengers')

        if location == None:
            location = 'PVR Cinemas'
        self.__movie = movie
        self.__location = location

    def __str__(self) -> str:
        return f"movie = {self.__movie}, location = {self.__location}"

    def movie(self):
        return self.__movie

    def location(self):
        return self.__location

t1 = Ticket()

m1 = Movie('Justice League')
t2 = Ticket(movie=m1)

When to use objects or something else

  • Objects are most useful when we need a number of individual instances that have similar behaviour (methods), but differ in their internal states (attributes)
  • If you have a number of variables that contain multiple values and can be passed as arguments to multiple functions, it might be better to define a class
  • Use the simplest solution to the problem, A dictionary, list or tuple is simpler, smaller and faster that module, which is usually simpler than a class

Named Tuples

  • Python supports a type of container like dictionaries called as namedtuple
from collections import namedtuple

Movie = namedtuple('Movie', ['name', 'genre', 'director'])
avengers = Movie(name='Avengers', genre=['Action', 'Adventure', 'Sci-fi'], director='Joss Whedon')
justice_league = Movie(name='Justice Leagure', genre=['Action', 'Adventure', 'Fantasy'], director='Zack Synder')
def print_movie_info(movie):
    print(f"Name={} genre={movie.genre} director={movie.director}")
  • Refer Here for the changeset containing the named tuple and composition example

Data classes

  • Many like to create objects mainly to store data (attributes), not so much behavior (methods). We have seen how named tuples can alternatively store data.
  • Python 3.7 data classes were introduced
  • Refer Here for the code created in the class


  • Create a named tuple to store the Student information
    • name
    • address
    • courses
    • email id
  • Try to create a dataclasses to represent the above Student Structure

Decorators in Python

  • Sometimes, you want to modify an existing function without changing its source code
  • Refer Here for the decorator sample used in the class

Namespaces and Scope

  • Scope resolution for variable names via LEGB
    • Local can be inside a function or method
    • Enclosed can be inside enclose function i.e function which is wrapped inside other functions
    • Global refers to uppermost level of executing python script/file
    • Built-in are special names that Python reserves for itself
animal = 'Tiger'

def local_function():
    animal = 'Lion'
    print(f"Locals are {locals()}")
    print(f"Globals are {globals()}")


def change_global():
    global animal
    animal = 'Lion'


Leave a Comment

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

About learningthoughtsadmin