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 - object oriented
Python - object orientedPython - object oriented
Python - object oriented
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
python Function
python Function python Function
python Function
 
Introduction To Python | Edureka
Introduction To Python | EdurekaIntroduction To Python | Edureka
Introduction To Python | Edureka
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
 
Function Parameters
Function ParametersFunction Parameters
Function Parameters
 
Python OOPs
Python OOPsPython OOPs
Python OOPs
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
 
Functions in Python
Functions in PythonFunctions in Python
Functions in Python
 
Python functions
Python functionsPython functions
Python functions
 
Python Flow Control
Python Flow ControlPython Flow Control
Python Flow Control
 
Python Course for Beginners
Python Course for BeginnersPython Course for Beginners
Python Course for Beginners
 
Function in Python
Function in PythonFunction in Python
Function in Python
 
Introduction to Named Entity Recognition
Introduction to Named Entity RecognitionIntroduction to Named Entity Recognition
Introduction to Named Entity Recognition
 
Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Functions in python
Functions in pythonFunctions in python
Functions in python
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
 
Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3Ppl for students unit 1,2 and 3
Ppl for students unit 1,2 and 3
 
Python : Data Types
Python : Data TypesPython : Data Types
Python : Data Types
 
Object Oriented Programming Lecture Notes
Object Oriented Programming Lecture NotesObject Oriented Programming Lecture Notes
Object Oriented Programming Lecture Notes
 

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
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 

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_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
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 

Recently uploaded

cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningVitsRangannavar
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 

Recently uploaded (20)

cybersecurity notes for mca students for learning
cybersecurity notes for mca students for learningcybersecurity notes for mca students for learning
cybersecurity notes for mca students for learning
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 

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.