SlideShare a Scribd company logo
1 of 40
Advanced Python
Pulkit Agrawal
Agenda:
1. How Everything in python is Object?
2. Comprehension (Multiple and Nested)
3. Extended Keyword Arguments(*args, **kwargs)
4. Closure and Decorators
5. Generators and Iterators Protocol
6. Context Managers
7. @staticmethod, @classmethod
8. Inheritance and Encapsulation
9. Operator Overloading
10.Python packages and Program Layout
1. How Everything in python is Object?
Strings are objects. Lists are objects. Functions are objects. Even modules are objects.
everything is an object in the sense that it can be assigned to a variable or passed as an
argument to a function.
Anything you can (legally) place on the right hand side of the equals sign is (or creates) an
object in Python.
>> def hello():
>> hi = hello()
>> hi()
Objects
That has:
1. An Identity(id)
2. A value(mutable or immutable)
I. Mautable: When you alter the item, the id is still the same. Ex: Dictionary, List
II. Immutable: String, Integer, tuple
2. Comprehension
short-hand syntax for creating collections and iterable objects
1. List Comprehension => [ expr(item) for item in iterable ]
2. Set Comprehension => { expr(item) for item in iterable }
3. Dictionary Comprehension => { key_expr:value_expr for item in iterable }
4. Generator Comprehension => ( expr(item) for item in iterable)
5. If-clause => [ expr(item) for item in iterable if predicate(item) ]
6. Multiple Comprehension => [(x,y) for x in range(10) for y in range(3)]
7. Nested Comprehension => [[y*3 for y in range(x)] for x in range(10)]
3. Extended Arguments
Function Review:
Def function_name(arg1, arg2=1.0,):
BODY
Arg1 => Positional Argument
Arg2 => Keyword Argument
Extended Formal Argument Syntax
def extended(*args, **kwargs):
=>Arguments at the function definition side.
How we use print, format function?
Ex: print(“one”)
print(“one”, “two”)
We are passing any number of argument in print statement.
*args => tuple
**kwargs => dict
Way of writing:
Def func(arg1, arg2, *args, kwarg1, **kwargv):
Extended Actual Argument Syntax
Argument at the function call side.
extended(*args, **kwargs)
Ex: t = (1, 2, 3, 4)
Def print_arg(arg1, arg2, *args):
>> print_arg(*t)
4. Closure and Decorators
Local Function:
def func():
def local_func():
a = 'hello, '
b = 'world'
return a + b
x = 1
y = 2
return x + y
•Useful for specialized, one-off functions
•Aid in code organization and readability
•Similar to lambdas, but more general
• May contain multiple expressions
• May contain statements
Python follows LEGB Rule.
Returning Function :
def outer():
def inner():
print('inner')
return inner()
I = outer()
i()
Closures
Maintain references to object from earlier scopes.
def outer():
x = 3
def inner(y):
return x + y
return inner
>> i = outer() >> i.__closure__
We can use __closure__ to verify function is closure or not.
Decorators
Modify and enhance function without changing their definition.
Implement as callables that take and return other callable.
@my_decorator
def my_function():
We can also create classes as decorators and instances as decorators.
5. Generators and Iterable protocol
Iterable objects can be passed to the built-in iter() function to get an iterator.
Iterator objects can be passed to the built-in next() function to fetch the next item.
iterator = iter(iterable)
item = next(iterator)
Generators
Python generators are a simple way of creating iterators. All the overhead we
mentioned above are automatically handled by generators in Python.
A generator is a function that returns an object (iterator) which we can iterate over
(one value at a time).
If a function contains at least one yield statement it becomes a generator function.
The difference is that, while a return statement terminates a function entirely, yield
statement pauses the function saving all its states and later continues from there
on successive calls.
Why generators are used in Python?
1. Easy to Implement
2. Memory Efficient
3. Represent Infinite Stream
4. Pipelining Generators
def PowTwoGen(max = 0):
n = 0
while n < max:
yield 2 ** n
n += 1
6. Context Manager
context manager an object designed to be used in a with-statement.
A context-manager ensures that resources are properly and automatically
managed.
with context-manager:
context-manager.begin()
Body
context-manager.end()
__enter__()
• called before entering with-statement body
• return value bound to as variable
• can return value of any type
• commonly returns context-manager itself
__exit__()
called when with-statement body exits
__exit__(self, exc_type, exc_val, exc_tb)
7. @staticmethod, @classmethod
class attributes versus instance attributes:
Class A:
CLASS_ATTRIBUTE = 1
Def __init__(slef, instance_attribute):
Self.instance_attribute = instance_attribute
If you need to access class attributes within the function, prefer to use
@classmethod.
If don’t need to use cls object than use @static method.
Unlike other language, In python static method can be overridden in subclass.
8. Inheritance and Encapsulation
Inheritance
single inheritance:
class SubClass(BaseClass)
> Subclass will have all functionality of base class and it can also modify and
enhance.
>subclass initializer want to call base class initializer to make sense that the full
object is initialized.
Calling other class initializer
• Other languages automatically call base class initializers
• Python treats __init__() like any other method
• Base class __init__() is not called if overridden
• Use super() to call base class __init__()
Isinstance(instance, class): Determine if an object is of a specified type.
Issubclass(subclass, baseclass): Determine if one type is subclass of other.
Multiple Inheritance
Defining a class with more than one base class.
Class SubClass(Base1, Base2, …):
How does python know which base class function should call?
Python Uses Method Resolution Order and super to do that.
__bases__ => a tuple of base classes
__mro__ => a tuple of mro ordering
method resolution order
ordering that determines method name lookup
• Commonly called “MRO”
• Methods may be defined in multiple places
• MRO is an ordering of the inheritance graph
• Actually quite simple
9. Operator Overloading
Python Operator work for built-in classes. But same operator behaves differently
with different types. For example, the + operator will, perform arithmetic addition
on two numbers, merge two lists and concatenate two strings.
Operator Expression Internally
Addition p1 + p2 p1.__add__(p2)
Subtraction p1 - p2 p1.__sub__(p2)
Multiplication p1 * p2 p1.__mul__(p2)
Power p1 ** p2 p1.__pow__(p2)
Less than p1 < p2 p1.__lt__(p2)
Less than or equal to p1 <= p2 p1.__le__(p2)
Python Package and Program Layout
Package a module which can contain other modules.
Sys.path list of directories Python searches for modules.
PYTHONPATH Environment variable listing paths added to sys.path .
1. Packages are modules that contain other modules.
2. Packages are generally implemented as directories containing a special
__init__.py file.
3. The __init__.py file is executed when the package is imported.
4. Packages can contain sub packages which themselves are implemented
with __init__.py files in directories.
5. The module objects for packages have a __path__ attribute.
absolute imports: imports which use a full path to the module
from reader.reader import Reader
relative imports: imports which use a relative path to modules in the same
package.
from .reader import Reader
__all__: list of attribute names imported via from module import *
Thank You

More Related Content

What's hot (20)

Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Python for loop
Python for loopPython for loop
Python for loop
 
Begin with Python
Begin with PythonBegin with Python
Begin with Python
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Input and output in C++
Input and output in C++Input and output in C++
Input and output in C++
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
Python
PythonPython
Python
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Python
PythonPython
Python
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Introduction To Python | Edureka
Introduction To Python | EdurekaIntroduction To Python | Edureka
Introduction To Python | Edureka
 
Lex (lexical analyzer)
Lex (lexical analyzer)Lex (lexical analyzer)
Lex (lexical analyzer)
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
 
Exception handling in python
Exception handling in pythonException handling in python
Exception handling in python
 
Python quick guide1
Python quick guide1Python quick guide1
Python quick guide1
 
Python
PythonPython
Python
 
Function arguments In Python
Function arguments In PythonFunction arguments In Python
Function arguments In Python
 
Python Modules
Python ModulesPython Modules
Python Modules
 

Similar to Advance python

Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfprasnt1
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2Prerna Sharma
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answerskavinilavuG
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptxAshwini Raut
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...Maulik Borsaniya
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdfDaddy84
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndEdward Chen
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2sadhana312471
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experiencedzynofustechnology
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
Interview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfInterview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfExaminationSectionMR
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 

Similar to Advance python (20)

Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
 
Programming in C sesion 2
Programming in C sesion 2Programming in C sesion 2
Programming in C sesion 2
 
Functions2.pptx
Functions2.pptxFunctions2.pptx
Functions2.pptx
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Functions and Modules.pptx
Functions and Modules.pptxFunctions and Modules.pptx
Functions and Modules.pptx
 
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...PYTHON -Chapter 2 - Functions,   Exception, Modules  and    Files -MAULIK BOR...
PYTHON -Chapter 2 - Functions, Exception, Modules and Files -MAULIK BOR...
 
functions-.pdf
functions-.pdffunctions-.pdf
functions-.pdf
 
Functions2.pdf
Functions2.pdfFunctions2.pdf
Functions2.pdf
 
CS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2ndCS225_Prelecture_Notes 2nd
CS225_Prelecture_Notes 2nd
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experienced
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
Python_Functions_Unit1.pptx
Python_Functions_Unit1.pptxPython_Functions_Unit1.pptx
Python_Functions_Unit1.pptx
 
Interview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfInterview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdf
 
Python functions
Python functionsPython functions
Python functions
 
Python_UNIT-I.pptx
Python_UNIT-I.pptxPython_UNIT-I.pptx
Python_UNIT-I.pptx
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 

Recently uploaded

Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...software pro Development
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...kalichargn70th171
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfryanfarris8
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech studentsHimanshiGarg82
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 

Recently uploaded (20)

Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...How to Choose the Right Laravel Development Partner in New York City_compress...
How to Choose the Right Laravel Development Partner in New York City_compress...
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students8257 interfacing 2 in microprocessor for btech students
8257 interfacing 2 in microprocessor for btech students
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 

Advance python

  • 2. Agenda: 1. How Everything in python is Object? 2. Comprehension (Multiple and Nested) 3. Extended Keyword Arguments(*args, **kwargs) 4. Closure and Decorators 5. Generators and Iterators Protocol 6. Context Managers 7. @staticmethod, @classmethod 8. Inheritance and Encapsulation 9. Operator Overloading 10.Python packages and Program Layout
  • 3. 1. How Everything in python is Object? Strings are objects. Lists are objects. Functions are objects. Even modules are objects. everything is an object in the sense that it can be assigned to a variable or passed as an argument to a function. Anything you can (legally) place on the right hand side of the equals sign is (or creates) an object in Python. >> def hello(): >> hi = hello() >> hi()
  • 4. Objects That has: 1. An Identity(id) 2. A value(mutable or immutable) I. Mautable: When you alter the item, the id is still the same. Ex: Dictionary, List II. Immutable: String, Integer, tuple
  • 5.
  • 6. 2. Comprehension short-hand syntax for creating collections and iterable objects 1. List Comprehension => [ expr(item) for item in iterable ] 2. Set Comprehension => { expr(item) for item in iterable } 3. Dictionary Comprehension => { key_expr:value_expr for item in iterable } 4. Generator Comprehension => ( expr(item) for item in iterable) 5. If-clause => [ expr(item) for item in iterable if predicate(item) ] 6. Multiple Comprehension => [(x,y) for x in range(10) for y in range(3)] 7. Nested Comprehension => [[y*3 for y in range(x)] for x in range(10)]
  • 7. 3. Extended Arguments Function Review: Def function_name(arg1, arg2=1.0,): BODY Arg1 => Positional Argument Arg2 => Keyword Argument
  • 8. Extended Formal Argument Syntax def extended(*args, **kwargs): =>Arguments at the function definition side. How we use print, format function? Ex: print(“one”) print(“one”, “two”) We are passing any number of argument in print statement.
  • 9. *args => tuple **kwargs => dict Way of writing: Def func(arg1, arg2, *args, kwarg1, **kwargv):
  • 10. Extended Actual Argument Syntax Argument at the function call side. extended(*args, **kwargs) Ex: t = (1, 2, 3, 4) Def print_arg(arg1, arg2, *args): >> print_arg(*t)
  • 11. 4. Closure and Decorators Local Function: def func(): def local_func(): a = 'hello, ' b = 'world' return a + b x = 1 y = 2 return x + y
  • 12. •Useful for specialized, one-off functions •Aid in code organization and readability •Similar to lambdas, but more general • May contain multiple expressions • May contain statements Python follows LEGB Rule.
  • 13. Returning Function : def outer(): def inner(): print('inner') return inner() I = outer() i()
  • 14. Closures Maintain references to object from earlier scopes. def outer(): x = 3 def inner(y): return x + y return inner >> i = outer() >> i.__closure__ We can use __closure__ to verify function is closure or not.
  • 15. Decorators Modify and enhance function without changing their definition. Implement as callables that take and return other callable. @my_decorator def my_function(): We can also create classes as decorators and instances as decorators.
  • 16.
  • 17. 5. Generators and Iterable protocol Iterable objects can be passed to the built-in iter() function to get an iterator. Iterator objects can be passed to the built-in next() function to fetch the next item. iterator = iter(iterable) item = next(iterator)
  • 18. Generators Python generators are a simple way of creating iterators. All the overhead we mentioned above are automatically handled by generators in Python. A generator is a function that returns an object (iterator) which we can iterate over (one value at a time). If a function contains at least one yield statement it becomes a generator function. The difference is that, while a return statement terminates a function entirely, yield statement pauses the function saving all its states and later continues from there on successive calls.
  • 19. Why generators are used in Python? 1. Easy to Implement 2. Memory Efficient 3. Represent Infinite Stream 4. Pipelining Generators def PowTwoGen(max = 0): n = 0 while n < max: yield 2 ** n n += 1
  • 20. 6. Context Manager context manager an object designed to be used in a with-statement. A context-manager ensures that resources are properly and automatically managed. with context-manager: context-manager.begin() Body context-manager.end()
  • 21.
  • 22. __enter__() • called before entering with-statement body • return value bound to as variable • can return value of any type • commonly returns context-manager itself __exit__() called when with-statement body exits __exit__(self, exc_type, exc_val, exc_tb)
  • 23. 7. @staticmethod, @classmethod class attributes versus instance attributes: Class A: CLASS_ATTRIBUTE = 1 Def __init__(slef, instance_attribute): Self.instance_attribute = instance_attribute
  • 24.
  • 25. If you need to access class attributes within the function, prefer to use @classmethod. If don’t need to use cls object than use @static method. Unlike other language, In python static method can be overridden in subclass.
  • 26. 8. Inheritance and Encapsulation
  • 27. Inheritance single inheritance: class SubClass(BaseClass) > Subclass will have all functionality of base class and it can also modify and enhance. >subclass initializer want to call base class initializer to make sense that the full object is initialized.
  • 28. Calling other class initializer • Other languages automatically call base class initializers • Python treats __init__() like any other method • Base class __init__() is not called if overridden • Use super() to call base class __init__() Isinstance(instance, class): Determine if an object is of a specified type. Issubclass(subclass, baseclass): Determine if one type is subclass of other.
  • 29. Multiple Inheritance Defining a class with more than one base class. Class SubClass(Base1, Base2, …): How does python know which base class function should call? Python Uses Method Resolution Order and super to do that. __bases__ => a tuple of base classes __mro__ => a tuple of mro ordering
  • 30. method resolution order ordering that determines method name lookup • Commonly called “MRO” • Methods may be defined in multiple places • MRO is an ordering of the inheritance graph • Actually quite simple
  • 31.
  • 32.
  • 33. 9. Operator Overloading Python Operator work for built-in classes. But same operator behaves differently with different types. For example, the + operator will, perform arithmetic addition on two numbers, merge two lists and concatenate two strings.
  • 34. Operator Expression Internally Addition p1 + p2 p1.__add__(p2) Subtraction p1 - p2 p1.__sub__(p2) Multiplication p1 * p2 p1.__mul__(p2) Power p1 ** p2 p1.__pow__(p2) Less than p1 < p2 p1.__lt__(p2) Less than or equal to p1 <= p2 p1.__le__(p2)
  • 35. Python Package and Program Layout Package a module which can contain other modules.
  • 36. Sys.path list of directories Python searches for modules. PYTHONPATH Environment variable listing paths added to sys.path .
  • 37. 1. Packages are modules that contain other modules. 2. Packages are generally implemented as directories containing a special __init__.py file. 3. The __init__.py file is executed when the package is imported. 4. Packages can contain sub packages which themselves are implemented with __init__.py files in directories. 5. The module objects for packages have a __path__ attribute.
  • 38. absolute imports: imports which use a full path to the module from reader.reader import Reader relative imports: imports which use a relative path to modules in the same package. from .reader import Reader __all__: list of attribute names imported via from module import *
  • 39.