SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
Mixing it all up with Python
We shall discuss
● Classes
● New style classes
● Inheritace heirarchy and MRO
● Mixins
● Meta Classes
Classes
● Blueprints for creating an object
● Objects have properties(attributes) and
actions(methods)
● Python Classes are a little more than that, but
we shall see that later on
● Lets discuss on class definition
Class
class MyClass(BaseClass1, BaseClass2):
def __init__(self, attr1, attr2):
self.attr1 = attr1
self.attr2 = attr2
def do_something(self):
Print 'doing something...'
Stuff to discuss
● If there are no base classes you need not include
the braces after the class name
● object initialization is done in __init__(constructor)
● first argument to the method is the object itself.
Although it is customary to call the first argument
'self' it is not necessary
● The object has already been created by the time
__init__ is called
New style classes
● Introduced in python 2.2
● Inherit from 'object'
● Yes 'object' is actually a class, which act as the
base class of new style classes
● And yes in python a class is also an object
● Never mind...
● In python 3 all classes are new style even if you
do not explicitly inherit 'object'
New style class
class MyClass(object):
def __init__(self, attr1, attr2):
super(MyClass, self).__init__()
self.attr1 = attr1
self.attr2 = attr2
def do_something(self):
Print 'doing something...'
What is the benifit of new style
classes
● type class unification
● you can now subclass list, dict etc and create a
custom type that has all qualities of a builtin
with some extra functionality
● Follow on for more benifits
Old vs New
class X:
def __init__(self, value):
self.value = value
def __eq__(self, other):
return self.value == other.value
class X(object):
def __init__(self, value):
super(X, self).__init__()
self.value = value
def __eq__(self, other):
return self.value == other.value
Beginners better not
● If you want to alter the object creation you are looking
for __new__()
● Unlike __init__, __new__ is a staticmethod that
receives the class itself as its first argument.
● This is used to alter the object creation process itself
● Used only when you have to subclass imutables
● The __init__ method of the newly created object is
invoked only if __new__ returns an object of the
class's type
example
class X(str):
def __new__(cls, arg1):
return str.__new__(cls, arg1.upper())
def __init__(self, my_text):
self.original_text = my_text
Class Customization
● You can customize your classes with
– __eq__, __ne__, __lt__, __gt__, __le__, __ge__,
__cmp__,
– __nonzero__ called when you do bool(yourObject)
– If __nonzero__ does not exist __len__ is tried
– If both do not exist all values are assumed to be
possitive
● reference
MRO
● Defines where the interpreter looks, in the
inheritance chain, for a method when invoked
on an object
● It is the same logic for attributes although it is
named MRO
● Python 2.2 would do a depth first left to right
C3 algorithm
● Introduced in 2.3
● A MRO is bad when it breaks such fundamental properties
as
– local precedence ordering
● The order of base classes as defined by user
– Monotonicity
● A MRO is monotonic when the following is true: if C1 precedes C2 in the
linearization of C, then C1 precedes C2 in the linearization of any subclass
of C
● 2.3 Will raise an TypeError when you define a bad MRO
● reference
A Bad MRO
class X(object):
pass
class Y(object):
pass
class A(X, Y):
pass
class B(Y, X):
pass
class C(A, B):
pass
C3 Algorithm
take the head of the first list, if this head is not in the
tail of any of the other lists, then add it to the
linearization of C and remove it from the lists in the
merge, otherwise look at the head of the next list
and take it, if it is a good head. Then repeat the
operation until all the class are removed or it is
impossible to find good heads. In this case, it is
impossible to construct the merge, Python 2.3 will
refuse to create the class C and will raise an
exception.
Appy to our example
MRO(A) = AXYO
MRO(B) = BYXO
MRO(C) = C , AXYO, BYXO, AB
MRO(C) = C, A, XYO, BYXO, B
MRO(C) = C, A, B, XYO, YXO
Error- X appears in tail position in YXO and Y appears in
tail position in XYO
Mixins
● A form of inheritance where your bases implement a few
methods
– That can be mixed with out affecting the inheriting class, but
adding more features
– That may call methods that may not be defined in the same class
● Mixins are not classes that can be instantiated
● Used when implementing a logic involving optional
features, extended features etc
● Not very usefull unless you want to create a class from a
bunch of mixin classes at run time
Meta Classes
● It is the class of a class
● Allows creation of class at run time
● Possible because in python everything is an
object includng class and hence can be created
and modified at run time
● 'type()' is not a function, its a metaclass
● And yes metaclass can be subclassed
● reference
examples
a = str('hello world')
type(a)
type(type(a))
str.__class__
new_str = type('new_string_type', (str,), {'creator':
'akilesh})
new_str.__mro__
Mixing up
class dancer(object):
def dance(self):
print 'I am dancing'
class singer(object):
def sing(self):
print 'I am singing'
class gunner(object):
def gun_me_down(self):
print 'you better run'
performer = type('performer', (dancer,
singer, gunner), {'name': 'akilesh'})
Mr_T = performer()
Mr_T.name
Mr_T.sing()
Mr_T.dance()
Mr_T.gun_me_down()
Thank You
Ageeleshwar K
akilesh1597@gmail.com

Mais conteúdo relacionado

Mais procurados

Mais procurados (12)

Classes,object and methods jav
Classes,object and methods javClasses,object and methods jav
Classes,object and methods jav
 
البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية
 
C,s&s
C,s&sC,s&s
C,s&s
 
Metaprogramming in Ruby
Metaprogramming in RubyMetaprogramming in Ruby
Metaprogramming in Ruby
 
Keyword of java
Keyword of javaKeyword of java
Keyword of java
 
Inheritance Mixins & Traits
Inheritance Mixins & TraitsInheritance Mixins & Traits
Inheritance Mixins & Traits
 
Review of c_sharp2_features_part_i
Review of c_sharp2_features_part_iReview of c_sharp2_features_part_i
Review of c_sharp2_features_part_i
 
Reflection and Introspection
Reflection and IntrospectionReflection and Introspection
Reflection and Introspection
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 
‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism
 
Java
JavaJava
Java
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكال
 

Semelhante a Python data modelling

Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov
 

Semelhante a Python data modelling (20)

Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptx
 
Metaclasses – Python’s Object-Oriented Paradigm and Its Metaprogramming
Metaclasses – Python’s Object-Oriented Paradigm and Its MetaprogrammingMetaclasses – Python’s Object-Oriented Paradigm and Its Metaprogramming
Metaclasses – Python’s Object-Oriented Paradigm and Its Metaprogramming
 
Reflection
ReflectionReflection
Reflection
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5
 
Ruby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for rubyRuby object model - Understanding of object play role for ruby
Ruby object model - Understanding of object play role for ruby
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 
Python3
Python3Python3
Python3
 
Pythonclass
PythonclassPythonclass
Pythonclass
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdfPython Classes_ Empowering Developers, Enabling Breakthroughs.pdf
Python Classes_ Empowering Developers, Enabling Breakthroughs.pdf
 
Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013Ruby object model at the Ruby drink-up of Sophia, January 2013
Ruby object model at the Ruby drink-up of Sophia, January 2013
 
Python_Unit_3.pdf
Python_Unit_3.pdfPython_Unit_3.pdf
Python_Unit_3.pdf
 
Unit3 part1-class
Unit3 part1-classUnit3 part1-class
Unit3 part1-class
 
Python Metaclasses
Python MetaclassesPython Metaclasses
Python Metaclasses
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
 
python.pptx
python.pptxpython.pptx
python.pptx
 

Último

+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
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
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
VishalKumarJha10
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
VictorSzoltysek
 

Último (20)

+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...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
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
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
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
 
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
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM TechniquesAI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
AI Mastery 201: Elevating Your Workflow with Advanced LLM Techniques
 
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
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
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 

Python data modelling

  • 1. Mixing it all up with Python
  • 2. We shall discuss ● Classes ● New style classes ● Inheritace heirarchy and MRO ● Mixins ● Meta Classes
  • 3. Classes ● Blueprints for creating an object ● Objects have properties(attributes) and actions(methods) ● Python Classes are a little more than that, but we shall see that later on ● Lets discuss on class definition
  • 4. Class class MyClass(BaseClass1, BaseClass2): def __init__(self, attr1, attr2): self.attr1 = attr1 self.attr2 = attr2 def do_something(self): Print 'doing something...'
  • 5. Stuff to discuss ● If there are no base classes you need not include the braces after the class name ● object initialization is done in __init__(constructor) ● first argument to the method is the object itself. Although it is customary to call the first argument 'self' it is not necessary ● The object has already been created by the time __init__ is called
  • 6. New style classes ● Introduced in python 2.2 ● Inherit from 'object' ● Yes 'object' is actually a class, which act as the base class of new style classes ● And yes in python a class is also an object ● Never mind... ● In python 3 all classes are new style even if you do not explicitly inherit 'object'
  • 7. New style class class MyClass(object): def __init__(self, attr1, attr2): super(MyClass, self).__init__() self.attr1 = attr1 self.attr2 = attr2 def do_something(self): Print 'doing something...'
  • 8. What is the benifit of new style classes ● type class unification ● you can now subclass list, dict etc and create a custom type that has all qualities of a builtin with some extra functionality ● Follow on for more benifits
  • 9. Old vs New class X: def __init__(self, value): self.value = value def __eq__(self, other): return self.value == other.value class X(object): def __init__(self, value): super(X, self).__init__() self.value = value def __eq__(self, other): return self.value == other.value
  • 10. Beginners better not ● If you want to alter the object creation you are looking for __new__() ● Unlike __init__, __new__ is a staticmethod that receives the class itself as its first argument. ● This is used to alter the object creation process itself ● Used only when you have to subclass imutables ● The __init__ method of the newly created object is invoked only if __new__ returns an object of the class's type
  • 11. example class X(str): def __new__(cls, arg1): return str.__new__(cls, arg1.upper()) def __init__(self, my_text): self.original_text = my_text
  • 12. Class Customization ● You can customize your classes with – __eq__, __ne__, __lt__, __gt__, __le__, __ge__, __cmp__, – __nonzero__ called when you do bool(yourObject) – If __nonzero__ does not exist __len__ is tried – If both do not exist all values are assumed to be possitive ● reference
  • 13. MRO ● Defines where the interpreter looks, in the inheritance chain, for a method when invoked on an object ● It is the same logic for attributes although it is named MRO ● Python 2.2 would do a depth first left to right
  • 14. C3 algorithm ● Introduced in 2.3 ● A MRO is bad when it breaks such fundamental properties as – local precedence ordering ● The order of base classes as defined by user – Monotonicity ● A MRO is monotonic when the following is true: if C1 precedes C2 in the linearization of C, then C1 precedes C2 in the linearization of any subclass of C ● 2.3 Will raise an TypeError when you define a bad MRO ● reference
  • 15. A Bad MRO class X(object): pass class Y(object): pass class A(X, Y): pass class B(Y, X): pass class C(A, B): pass
  • 16. C3 Algorithm take the head of the first list, if this head is not in the tail of any of the other lists, then add it to the linearization of C and remove it from the lists in the merge, otherwise look at the head of the next list and take it, if it is a good head. Then repeat the operation until all the class are removed or it is impossible to find good heads. In this case, it is impossible to construct the merge, Python 2.3 will refuse to create the class C and will raise an exception.
  • 17. Appy to our example MRO(A) = AXYO MRO(B) = BYXO MRO(C) = C , AXYO, BYXO, AB MRO(C) = C, A, XYO, BYXO, B MRO(C) = C, A, B, XYO, YXO Error- X appears in tail position in YXO and Y appears in tail position in XYO
  • 18. Mixins ● A form of inheritance where your bases implement a few methods – That can be mixed with out affecting the inheriting class, but adding more features – That may call methods that may not be defined in the same class ● Mixins are not classes that can be instantiated ● Used when implementing a logic involving optional features, extended features etc ● Not very usefull unless you want to create a class from a bunch of mixin classes at run time
  • 19. Meta Classes ● It is the class of a class ● Allows creation of class at run time ● Possible because in python everything is an object includng class and hence can be created and modified at run time ● 'type()' is not a function, its a metaclass ● And yes metaclass can be subclassed ● reference
  • 20. examples a = str('hello world') type(a) type(type(a)) str.__class__ new_str = type('new_string_type', (str,), {'creator': 'akilesh}) new_str.__mro__
  • 21. Mixing up class dancer(object): def dance(self): print 'I am dancing' class singer(object): def sing(self): print 'I am singing' class gunner(object): def gun_me_down(self): print 'you better run' performer = type('performer', (dancer, singer, gunner), {'name': 'akilesh'}) Mr_T = performer() Mr_T.name Mr_T.sing() Mr_T.dance() Mr_T.gun_me_down()