SlideShare a Scribd company logo
Object Oriented ython
rograming
P
Instructions
I hope You enjoyed my previous slides. Please share your feedbacks by like/share/subscribing to my youtube
channel and give me chance to help you better.
PYTHON
High level object oriented programing
language, which is easy to learn/use and
very very readable.
PREREQUISITES
Some basic knowledge on programing.
Basic python knowledge.
Interest and patience.
More info on how to use contact me via email binayray2009@gmail.com
Hello!
I am Binay
I hope you will enjoy this presentation. For any
question find me @binayray2009 on twitter.
1.
Introduction to OOP
The real power of python
Big concept
Controlling complexity is the essence of
computer programming..
Class variable, methods & data member
Abstraction
Encapsulation/Interface
Composition
Inheritance/Derivation/Hierarchy
MRO
Generalization/Specialization
Polymorphism
Introspection/Reflection
Magic Functions
Built-in Functions
Private/protected attributes.
Delegation
Metaclasses
Contents in detail
2.
Class variable, methods & data member
Members of the great concept
Class and It’s Members
Here we discuss about the
members of a class.
Typically data members,
methods, static members
and static methods
mainly.
All data members and
methods are accessed by
the class itself with the
help of self keyword.
You can define attribute of
a class directly inside it or
instantiate inside init or
define it inside any other
class method.
Basically you can put any
type of method inside a
class but only methods
having self passed as an
argument can access the
class members such as
other methods data
members etc. To access
static members we pass
cls and access through it.
Class is the blueprint out of which real objects are born
3.
Abstraction
How things were started
Abstraction
Abstraction refers to the modeling of essential aspects, behaviour and characteristics
of real-world problems and entities, providing a relevant subset as the definition of a
programmatic structure that can realize such models. Abstraction not only contain the
data attributes of such a model, but also provides interfaces with the data. An
implementation of such an abstraction is the realization of that data and the interfaces
that go along with it. Such a realization should remain hidden from and irrelevant to the
client programmer.
4.
Encapsulation/Interface
Data Hiding
Data Encapsulation
Encapsulation describes the concept of data/information hiding and providing
interfaces or accessor functions to the data attributes. Direct access to data by any
client, bypassing the interfaces, goes against the principles of encapsulation, but the
programmer is free to allow such access. As a part of the implementation, the client
should not even know how the data attributes are architected within the abstraction. In
Python all class attributes are public, but names may be “mangled” to discourage
unauthorized access, but otherwise not prevented. It is up to the designer to provide the
appropriate interfaces to the data so that the client programmer does not have to resort
to manipulating the encapsulated data attributes.
5.
Composition
Real world combinations
Composition
Composition extends our description of classes, enabling multiple yet distinct classes to be
combined into a larger entity to solve a real world problem. Composition describes a singular,
complex systems such as a class made up of other smaller components such as other classes, data
attributes and behaviours, all of which are combined, embodying “has-a” relationships. For example,
the RepairShop “has-a” Mechanic and also “has-a” Customer.
Creating composite objects enables such additional functionality and makes sense because the
classes have nothing in common. Each classes have it’s own namespace and behaviour. When there
are more intimate relations between objects, the concept of derivation may make more sense in your
application, especially if you require like objects, with slightly different functionality.
Combinations and work done
class Math3(object):
. . . : def __init__(self,x,y):
. . . : self.x=x
. . . : self.y=y
. . . : self.m1=Math(x,y)
. . . : self.m2=Math1(x,y)
. . . : def power(self):
. . . : return self.x**self.y
. . . : def add(self):
. . . : return self.m1.add()
. . . : def subtract(self):
. . . : return self.m1.subtract()
. . . : def multiply(self):
. . . : return self.m2.multiply()
>>> class Math1(object):
. . . : def __init__(self,x,y):
. . . : self.x=x
. . . : self.y=y
. . . : def add(self):
. . . : return self.x+self.y
. . . : def subtract(self):
. . . : return self.x-self.y
class Math1(object):
. . . : def __init__(self,x,y):
. . . : self.x=x
. . . : self.y=y
. . . : def multiply(self):
. . . : return self.x*self.y
. . . : def divide(self):
. . . : return self.x/self.y
>>> m = Math3(10,2)
>>> m.add()
12
>>> m.subtract()
8
>>> m.multiply()
20
>>> m.power()
100
>>> m.m2
<__main__.Math1 at 0x2ec1ed0>
>>> m.m2.devide()
5
6.
Inheritance/Derivation/Hierarchy
How things Works
Inheritance
Composition works fine when classes are
distinct and are a required component of
a larger class, But when you need the
same class with a small change in its
behaviour derivation comes handy.
class Person(object):
def parent_method(self):
print ‘Parent’
class Student(Person):
def
student_method(self):
print “Student”
>>> a = Person()
>>> b = Student()
>>> a.parent_method()
Parent
>>> b.student_method()
Student
>>> b.parent_method()
Parent
>>> Parent.__bases__
(object,)
>>> Student.__bases__
(__main__.Parent,)
Power of Super
class Parent(object):
def sayhi(self):
print ‘Parent’
class Student1(Parent):
def sayhi(self):
print ‘Student’
class Student2(Parent):
def sayhi(self):
super(Student2,
self).sayhi()
>>> p = Parent()
>>> s1 = Student1()
>>> p.sayhi()
Parent
>>> s1.sayhi()
Student
>>> s2.sayhi()
Parent
7.
MRO
Making generations together.
Examples
Parent
class P1:
pass
class P2:
def f00(self):
print
‘p2-foo’
def bar(self):
print
‘p2-bar’
Children
class C1(P1, P2):
pass
class C2(P1, P2):
def bar(self):
print ‘c2-
bar’
Grand Child
class GC(C1, C2):
Pass
Old Style
>>>gc = GC()
>>>gc.foo()
p2-foo
>>>gc.bar()
p2-bar
New Style
>>>gc = GC()
>>>gc.foo()
p2-foo
>>>gc.bar()
C2-bar
Old vs New
VS
Yes, It Fails
class A(object):
pass
class B(object):
def __init__(self, *args, **kwargs):
self.a = 10
class C(A, B):
pass
8.
Generalization/Specialization
Relate things to real world
Generalization/Specialization
Generalization describes all traits a subclass has with it’s parent and ancestor classes, so
subclasses are considered to have “is-a” relationship with ancestor classes because a derived
object(instance) is an example of an ancestor class. For example, a Mechanic “is-a” Person, a car “is-
a” Vehicle, etc. In the family tree diagram we alluded to above, we can draw lines from subclasses to
ancestors indicating “is-a” relationship. Specialization is the term that describes all the
customization of a subclass, ie what attributes make it differ from its ancestor classes.
9.
Polymorphism
Nothing lasts forever
Polymorphism
The concept of polymorphism describes how objects can be manipulated and accessed using
attributes and behaviours they have in common. Without regard to their specific class.
Polymorphism indicates the presence of dynamic binding, allowing for overriding and runtime type
determination and verification.
>>> a = list()
>>> a
[ ]
>>> a.append(5)
>>> a
[5]
>>> a.pop()
5
>>> a
[ ]
>>> a.extend([6])
>>>a
[6]
>>> class NewList(list):
…. def append(self, *args, **kwargs):
…. print args
>>> b = NewList()
>>> b
[ ]
>>> b.append(5)
(5, )
>>> b
[ ]
>>> b.extend([6])
>>> b
[6]
>>> b.pop()
6
>>> b
[ ]
10.
Introspection/Reflection
Me using myself
Introspection/Reflection
Introspection is what gives you, the programmer, the ability to perform an activity such as “manual
type checking”. Also called reflection, this property describes how information about a particular
object can be accessed by itself during runtime. Would it not be great to have the ability to make an
object passed to you and be able to find out what it is capable of? The dir() and type() built-in
functions would have a very difficult time working if python doesn't support some sort of
introspection capability. Keep an eye out for these calls as well as for special attributes like
__dict__, __name__, and __doc__. You may even be familiar with some of them already.
11.
Magic Functions
Because these creates magic
Special Methods
Out of many special
available methods i’m
going to describe a few,
which will surely help you
in future.
Examples
__init__
__new__
__del__
__str__
__repr__
__unicode__
__call__
__nonzero__
__len__
12.
Built-in Functions
Some awesome things are already there
Some built-in python functions make our life easy
Example:
issubclass(sub, sup) Returns True if sub is subclass of sup, False otherwise
isinstance(obj1, obj2) Returns True if obj1 is instance of class obj2, or subclass of obj2 or type of obj2.
hasattr(obj, attr) Returns True if obj has attribute attr.
getattr(obj, attr, [, default]) Retrieves attr of the object, if not found AttributeError is raised.
setattr(obj, attr, val) Sets attribute of obj to val overriding the previous values.
delattr(obj, attr) Deletes the attribute of the obj
dir(obj=None) Returns a list of attributes of obj. If obj is None, it displays local namespaces of attr.
super(type, obj=None) Returns a proxy object representing the super class.
vars(obj=None) Returns a dictionary of attr and values of obj.
13.
Private/protected attributes.
There are private things you don’t know
Privacy/Access Control
By Default all methods and attributes are public in python
classes. That means the class attributes can be used by both
the class and the code containing the import of that class.
Although Python doesn’t have syntax built into it for private,
protected, friend, protected friend, You can customize the access
the exact way that fits your need.
We will mainly see the differences of _ and __ in this lesson.
14.
Delegation
Boring stuff
Delegation is like a Friend
Delegation provides a proxy object
for any class that your want on top
of the main class. It’s like a
wrapper to your class so that you
can access limited resources of
the main class.
It wraps the object of main class
into a smaller object with limited
access.
>>> class A(object):
…. def sayhi(self):
…. return ‘Hello World’
>>> class B(object):
…. def __init__(self, obj):
…. self.human = obj
…. def welcome(self):
…. return self.human.sayhi()
15.
Metaclasses
Soul of python classes
Blueprint of the Blueprint
Metaclasses are the classes that creates other classes.
Does that mean every class is an object and every object is an
object of object?
Yes!!
Type is the metaclasses usually responsible for it but you can
create your own metaclass also.
Doubts? Please Ask.
Questions
&
Answers
Thanks!
Any questions?
You can find me at @binayray2009 &
binayray2009@gmail.com

More Related Content

What's hot (20)

PPTX
Object oriented programming with python
Arslan Arshad
 
PPTX
Exception Handling in object oriented programming using C++
Janki Shah
 
PPTX
Object Oriented Programming in Python
Sujith Kumar
 
PPTX
Class, object and inheritance in python
Santosh Verma
 
PPTX
Functions in python
colorsof
 
PPTX
File Handling Python
Akhil Kaushik
 
PDF
Python exception handling
Mohammed Sikander
 
PPTX
Python-DataAbstarction.pptx
Karudaiyar Ganapathy
 
PPTX
Chapter 05 classes and objects
Praveen M Jigajinni
 
PPTX
Static Data Members and Member Functions
MOHIT AGARWAL
 
PDF
File handling in Python
BMS Institute of Technology and Management
 
PDF
Constructors and destructors
Nilesh Dalvi
 
PPTX
Data Structures in Python
Devashish Kumar
 
PDF
Strings in python
Prabhakaran V M
 
PPSX
Modules and packages in python
TMARAGATHAM
 
PDF
Polymorphism In Java
Spotle.ai
 
PPTX
Constructor in java
Pavith Gunasekara
 
ODP
Python Modules
Nitin Reddy Katkam
 
PPT
Method overriding
Azaz Maverick
 
PPTX
Python-Functions.pptx
Karudaiyar Ganapathy
 
Object oriented programming with python
Arslan Arshad
 
Exception Handling in object oriented programming using C++
Janki Shah
 
Object Oriented Programming in Python
Sujith Kumar
 
Class, object and inheritance in python
Santosh Verma
 
Functions in python
colorsof
 
File Handling Python
Akhil Kaushik
 
Python exception handling
Mohammed Sikander
 
Python-DataAbstarction.pptx
Karudaiyar Ganapathy
 
Chapter 05 classes and objects
Praveen M Jigajinni
 
Static Data Members and Member Functions
MOHIT AGARWAL
 
Constructors and destructors
Nilesh Dalvi
 
Data Structures in Python
Devashish Kumar
 
Strings in python
Prabhakaran V M
 
Modules and packages in python
TMARAGATHAM
 
Polymorphism In Java
Spotle.ai
 
Constructor in java
Pavith Gunasekara
 
Python Modules
Nitin Reddy Katkam
 
Method overriding
Azaz Maverick
 
Python-Functions.pptx
Karudaiyar Ganapathy
 

Similar to Python OOPs (20)

PDF
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
PDF
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
PPTX
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
PPTX
مقدمة بايثون .pptx
AlmutasemBillahAlwas
 
PPTX
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
PPTX
OOP Concepts Python with code refrences.pptx
SofiMusic
 
PPTX
classes and objects of python object oriented
VineelaThonduri
 
PPTX
Python_Unit_2 OOPS.pptx
ChhaviCoachingCenter
 
PPTX
Lec-21-Classes and Object Orientation.pptx
resoj26651
 
PPT
Introduction to Python - Part Three
amiable_indian
 
PPTX
Unit – V Object Oriented Programming in Python.pptx
YugandharaNalavade
 
PPTX
Python lec4
Swarup Ghosh
 
PDF
Unit 3-Classes ,Objects and Inheritance.pdf
Harsha Patil
 
PPTX
OOPS 46 slide Python concepts .pptx
mrsam3062
 
PPTX
Python advance
Mukul Kirti Verma
 
PPT
07slide.ppt
NuurAxmed2
 
PDF
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
PPTX
Object Oriented Programming.pptx
SAICHARANREDDYN
 
PDF
Robust Python Write Clean And Maintainable Code 1st Edition Patrick Viafore
yunyunburm
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
SudhanshiBakre1
 
PYTHON-COURSE-PROGRAMMING-UNIT-IV--.pptx
mru761077
 
مقدمة بايثون .pptx
AlmutasemBillahAlwas
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
OOP Concepts Python with code refrences.pptx
SofiMusic
 
classes and objects of python object oriented
VineelaThonduri
 
Python_Unit_2 OOPS.pptx
ChhaviCoachingCenter
 
Lec-21-Classes and Object Orientation.pptx
resoj26651
 
Introduction to Python - Part Three
amiable_indian
 
Unit – V Object Oriented Programming in Python.pptx
YugandharaNalavade
 
Python lec4
Swarup Ghosh
 
Unit 3-Classes ,Objects and Inheritance.pdf
Harsha Patil
 
OOPS 46 slide Python concepts .pptx
mrsam3062
 
Python advance
Mukul Kirti Verma
 
07slide.ppt
NuurAxmed2
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 
Object Oriented Programming.pptx
SAICHARANREDDYN
 
Robust Python Write Clean And Maintainable Code 1st Edition Patrick Viafore
yunyunburm
 
Ad

Recently uploaded (20)

PDF
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
PPTX
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
PPTX
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
PPT
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
PPTX
sajflsajfljsdfljslfjslfsdfas;fdsfksadfjlsdflkjslgfs;lfjlsajfl;sajfasfd.pptx
theknightme
 
DOCX
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
PDF
BRKACI-1003 ACI Brownfield Migration - Real World Experiences and Best Practi...
fcesargonca
 
PDF
BRKACI-1001 - Your First 7 Days of ACI.pdf
fcesargonca
 
PDF
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
PPTX
一比一原版(SUNY-Albany毕业证)纽约州立大学奥尔巴尼分校毕业证如何办理
Taqyea
 
PPTX
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
PPTX
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
PPTX
Orchestrating things in Angular application
Peter Abraham
 
PPTX
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 
PDF
Azure_DevOps introduction for CI/CD and Agile
henrymails
 
PPTX
internet básico presentacion es una red global
70965857
 
PPT
introduction to networking with basics coverage
RamananMuthukrishnan
 
PPTX
Optimization_Techniques_ML_Presentation.pptx
farispalayi
 
PDF
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
PPTX
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 
𝐁𝐔𝐊𝐓𝐈 𝐊𝐄𝐌𝐄𝐍𝐀𝐍𝐆𝐀𝐍 𝐊𝐈𝐏𝐄𝐑𝟒𝐃 𝐇𝐀𝐑𝐈 𝐈𝐍𝐈 𝟐𝟎𝟐𝟓
hokimamad0
 
L1A Season 1 ENGLISH made by A hegy fixed
toszolder91
 
ONLINE BIRTH CERTIFICATE APPLICATION SYSYTEM PPT.pptx
ShyamasreeDutta
 
Agilent Optoelectronic Solutions for Mobile Application
andreashenniger2
 
sajflsajfljsdfljslfjslfsdfas;fdsfksadfjlsdflkjslgfs;lfjlsajfl;sajfasfd.pptx
theknightme
 
Custom vs. Off-the-Shelf Banking Software
KristenCarter35
 
BRKACI-1003 ACI Brownfield Migration - Real World Experiences and Best Practi...
fcesargonca
 
BRKACI-1001 - Your First 7 Days of ACI.pdf
fcesargonca
 
Cleaning up your RPKI invalids, presented at PacNOG 35
APNIC
 
一比一原版(SUNY-Albany毕业证)纽约州立大学奥尔巴尼分校毕业证如何办理
Taqyea
 
Presentation3gsgsgsgsdfgadgsfgfgsfgagsfgsfgzfdgsdgs.pptx
SUB03
 
L1A Season 1 Guide made by A hegy Eng Grammar fixed
toszolder91
 
Orchestrating things in Angular application
Peter Abraham
 
原版西班牙莱昂大学毕业证(León毕业证书)如何办理
Taqyea
 
Azure_DevOps introduction for CI/CD and Agile
henrymails
 
internet básico presentacion es una red global
70965857
 
introduction to networking with basics coverage
RamananMuthukrishnan
 
Optimization_Techniques_ML_Presentation.pptx
farispalayi
 
Apple_Environmental_Progress_Report_2025.pdf
yiukwong
 
PM200.pptxghjgfhjghjghjghjghjghjghjghjghjghj
breadpaan921
 
Ad

Python OOPs

  • 2. Instructions I hope You enjoyed my previous slides. Please share your feedbacks by like/share/subscribing to my youtube channel and give me chance to help you better. PYTHON High level object oriented programing language, which is easy to learn/use and very very readable. PREREQUISITES Some basic knowledge on programing. Basic python knowledge. Interest and patience. More info on how to use contact me via email [email protected]
  • 3. Hello! I am Binay I hope you will enjoy this presentation. For any question find me @binayray2009 on twitter.
  • 4. 1. Introduction to OOP The real power of python
  • 5. Big concept Controlling complexity is the essence of computer programming..
  • 6. Class variable, methods & data member Abstraction Encapsulation/Interface Composition Inheritance/Derivation/Hierarchy MRO Generalization/Specialization Polymorphism Introspection/Reflection Magic Functions Built-in Functions Private/protected attributes. Delegation Metaclasses Contents in detail
  • 7. 2. Class variable, methods & data member Members of the great concept
  • 8. Class and It’s Members Here we discuss about the members of a class. Typically data members, methods, static members and static methods mainly. All data members and methods are accessed by the class itself with the help of self keyword. You can define attribute of a class directly inside it or instantiate inside init or define it inside any other class method. Basically you can put any type of method inside a class but only methods having self passed as an argument can access the class members such as other methods data members etc. To access static members we pass cls and access through it. Class is the blueprint out of which real objects are born
  • 10. Abstraction Abstraction refers to the modeling of essential aspects, behaviour and characteristics of real-world problems and entities, providing a relevant subset as the definition of a programmatic structure that can realize such models. Abstraction not only contain the data attributes of such a model, but also provides interfaces with the data. An implementation of such an abstraction is the realization of that data and the interfaces that go along with it. Such a realization should remain hidden from and irrelevant to the client programmer.
  • 12. Data Encapsulation Encapsulation describes the concept of data/information hiding and providing interfaces or accessor functions to the data attributes. Direct access to data by any client, bypassing the interfaces, goes against the principles of encapsulation, but the programmer is free to allow such access. As a part of the implementation, the client should not even know how the data attributes are architected within the abstraction. In Python all class attributes are public, but names may be “mangled” to discourage unauthorized access, but otherwise not prevented. It is up to the designer to provide the appropriate interfaces to the data so that the client programmer does not have to resort to manipulating the encapsulated data attributes.
  • 14. Composition Composition extends our description of classes, enabling multiple yet distinct classes to be combined into a larger entity to solve a real world problem. Composition describes a singular, complex systems such as a class made up of other smaller components such as other classes, data attributes and behaviours, all of which are combined, embodying “has-a” relationships. For example, the RepairShop “has-a” Mechanic and also “has-a” Customer. Creating composite objects enables such additional functionality and makes sense because the classes have nothing in common. Each classes have it’s own namespace and behaviour. When there are more intimate relations between objects, the concept of derivation may make more sense in your application, especially if you require like objects, with slightly different functionality.
  • 15. Combinations and work done class Math3(object): . . . : def __init__(self,x,y): . . . : self.x=x . . . : self.y=y . . . : self.m1=Math(x,y) . . . : self.m2=Math1(x,y) . . . : def power(self): . . . : return self.x**self.y . . . : def add(self): . . . : return self.m1.add() . . . : def subtract(self): . . . : return self.m1.subtract() . . . : def multiply(self): . . . : return self.m2.multiply() >>> class Math1(object): . . . : def __init__(self,x,y): . . . : self.x=x . . . : self.y=y . . . : def add(self): . . . : return self.x+self.y . . . : def subtract(self): . . . : return self.x-self.y class Math1(object): . . . : def __init__(self,x,y): . . . : self.x=x . . . : self.y=y . . . : def multiply(self): . . . : return self.x*self.y . . . : def divide(self): . . . : return self.x/self.y >>> m = Math3(10,2) >>> m.add() 12 >>> m.subtract() 8 >>> m.multiply() 20 >>> m.power() 100 >>> m.m2 <__main__.Math1 at 0x2ec1ed0> >>> m.m2.devide() 5
  • 17. Inheritance Composition works fine when classes are distinct and are a required component of a larger class, But when you need the same class with a small change in its behaviour derivation comes handy. class Person(object): def parent_method(self): print ‘Parent’ class Student(Person): def student_method(self): print “Student” >>> a = Person() >>> b = Student() >>> a.parent_method() Parent >>> b.student_method() Student >>> b.parent_method() Parent >>> Parent.__bases__ (object,) >>> Student.__bases__ (__main__.Parent,)
  • 18. Power of Super class Parent(object): def sayhi(self): print ‘Parent’ class Student1(Parent): def sayhi(self): print ‘Student’ class Student2(Parent): def sayhi(self): super(Student2, self).sayhi() >>> p = Parent() >>> s1 = Student1() >>> p.sayhi() Parent >>> s1.sayhi() Student >>> s2.sayhi() Parent
  • 20. Examples Parent class P1: pass class P2: def f00(self): print ‘p2-foo’ def bar(self): print ‘p2-bar’ Children class C1(P1, P2): pass class C2(P1, P2): def bar(self): print ‘c2- bar’ Grand Child class GC(C1, C2): Pass
  • 21. Old Style >>>gc = GC() >>>gc.foo() p2-foo >>>gc.bar() p2-bar New Style >>>gc = GC() >>>gc.foo() p2-foo >>>gc.bar() C2-bar Old vs New VS
  • 22. Yes, It Fails class A(object): pass class B(object): def __init__(self, *args, **kwargs): self.a = 10 class C(A, B): pass
  • 24. Generalization/Specialization Generalization describes all traits a subclass has with it’s parent and ancestor classes, so subclasses are considered to have “is-a” relationship with ancestor classes because a derived object(instance) is an example of an ancestor class. For example, a Mechanic “is-a” Person, a car “is- a” Vehicle, etc. In the family tree diagram we alluded to above, we can draw lines from subclasses to ancestors indicating “is-a” relationship. Specialization is the term that describes all the customization of a subclass, ie what attributes make it differ from its ancestor classes.
  • 26. Polymorphism The concept of polymorphism describes how objects can be manipulated and accessed using attributes and behaviours they have in common. Without regard to their specific class. Polymorphism indicates the presence of dynamic binding, allowing for overriding and runtime type determination and verification. >>> a = list() >>> a [ ] >>> a.append(5) >>> a [5] >>> a.pop() 5 >>> a [ ] >>> a.extend([6]) >>>a [6] >>> class NewList(list): …. def append(self, *args, **kwargs): …. print args >>> b = NewList() >>> b [ ] >>> b.append(5) (5, ) >>> b [ ] >>> b.extend([6]) >>> b [6] >>> b.pop() 6 >>> b [ ]
  • 28. Introspection/Reflection Introspection is what gives you, the programmer, the ability to perform an activity such as “manual type checking”. Also called reflection, this property describes how information about a particular object can be accessed by itself during runtime. Would it not be great to have the ability to make an object passed to you and be able to find out what it is capable of? The dir() and type() built-in functions would have a very difficult time working if python doesn't support some sort of introspection capability. Keep an eye out for these calls as well as for special attributes like __dict__, __name__, and __doc__. You may even be familiar with some of them already.
  • 30. Special Methods Out of many special available methods i’m going to describe a few, which will surely help you in future. Examples __init__ __new__ __del__ __str__ __repr__ __unicode__ __call__ __nonzero__ __len__
  • 31. 12. Built-in Functions Some awesome things are already there
  • 32. Some built-in python functions make our life easy Example: issubclass(sub, sup) Returns True if sub is subclass of sup, False otherwise isinstance(obj1, obj2) Returns True if obj1 is instance of class obj2, or subclass of obj2 or type of obj2. hasattr(obj, attr) Returns True if obj has attribute attr. getattr(obj, attr, [, default]) Retrieves attr of the object, if not found AttributeError is raised. setattr(obj, attr, val) Sets attribute of obj to val overriding the previous values. delattr(obj, attr) Deletes the attribute of the obj dir(obj=None) Returns a list of attributes of obj. If obj is None, it displays local namespaces of attr. super(type, obj=None) Returns a proxy object representing the super class. vars(obj=None) Returns a dictionary of attr and values of obj.
  • 33. 13. Private/protected attributes. There are private things you don’t know
  • 34. Privacy/Access Control By Default all methods and attributes are public in python classes. That means the class attributes can be used by both the class and the code containing the import of that class. Although Python doesn’t have syntax built into it for private, protected, friend, protected friend, You can customize the access the exact way that fits your need. We will mainly see the differences of _ and __ in this lesson.
  • 36. Delegation is like a Friend Delegation provides a proxy object for any class that your want on top of the main class. It’s like a wrapper to your class so that you can access limited resources of the main class. It wraps the object of main class into a smaller object with limited access. >>> class A(object): …. def sayhi(self): …. return ‘Hello World’ >>> class B(object): …. def __init__(self, obj): …. self.human = obj …. def welcome(self): …. return self.human.sayhi()
  • 38. Blueprint of the Blueprint Metaclasses are the classes that creates other classes. Does that mean every class is an object and every object is an object of object? Yes!! Type is the metaclasses usually responsible for it but you can create your own metaclass also.