Composition in Python
- One Example Around Composition
class Movie:
def __init__(self, name):
self.__name = name
@property
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}"
@property
def movie(self):
return self.__movie
@property
def location(self):
return self.__location
t1 = Ticket()
print(t1)
m1 = Movie('Justice League')
t2 = Ticket(movie=m1)
print(t2)
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={movie.name} genre={movie.genre} director={movie.director}")
print_movie_info(avengers)
print_movie_info(justice_league)
- 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
Exercise
- 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(animal)
print(f"Locals are {locals()}")
print(f"Globals are {globals()}")
local_function()
def change_global():
global animal
animal = 'Lion'
print(animal)
change_global()
print(animal)
Like this:
Like Loading...