SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
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

Weitere ähnliche Inhalte

Was ist angesagt?

Classes,object and methods jav
Classes,object and methods javClasses,object and methods jav
Classes,object and methods javPadma Kannan
 
البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية البرمجة الهدفية بلغة جافا - مفاهيم أساسية
البرمجة الهدفية بلغة جافا - مفاهيم أساسية Mahmoud Alfarra
 
Keyword of java
Keyword of javaKeyword of java
Keyword of javaJani Harsh
 
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_iNico Ludwig
 
Reflection and Introspection
Reflection and IntrospectionReflection and Introspection
Reflection and Introspectionadil raja
 
‫‫Chapter4 Polymorphism
‫‫Chapter4 Polymorphism‫‫Chapter4 Polymorphism
‫‫Chapter4 PolymorphismMahmoud Alfarra
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالMahmoud Alfarra
 

Was ist angesagt? (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
 
البرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكالالبرمجة الهدفية بلغة جافا - تعدد الأشكال
البرمجة الهدفية بلغة جافا - تعدد الأشكال
 

Ähnlich wie Python data modelling

Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Bhanwar Singh Meena
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Threeamiable_indian
 
Object Oriented Programming.pptx
Object Oriented Programming.pptxObject Oriented Programming.pptx
Object Oriented Programming.pptxSAICHARANREDDYN
 
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 MetaprogrammingInexture Solutions
 
Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov, Introduction to Python, Lecture5
Anton Kasyanov, Introduction to Python, Lecture5Anton Kasyanov
 
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 rubyTushar Pal
 
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.pdfSudhanshiBakre1
 
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.pdfSudhanshiBakre1
 
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 2013rivierarb
 
Python_Unit_3.pdf
Python_Unit_3.pdfPython_Unit_3.pdf
Python_Unit_3.pdfalaparthi
 
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.pptmuneshwarbisen1
 

Ähnlich wie 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
 

Kürzlich hochgeladen

React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 

Kürzlich hochgeladen (20)

React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 

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()