SlideShare uma empresa Scribd logo
1 de 45
Baixar para ler offline
Dive into Python
ClassKnowing python class step-by-step
Created by /Jim Yeh @jimyeh00
About Me
A front-to-end web developer
Use Python since 2006
Enjoy writing python code
Outline
Introduce New-style class
descriptor
function
super
Basic knowing
Knowledge of OO
Classic class and new-style
class
Different syntax
type of object
Inheritance
Syntax
>>> class OldObj:
... pass
>>> type(OldObj)
<type 'classobj'>
>>> class NewObj(object):
... pass
>>> type(NewObj)
<type 'type'>
type of object
>>> old_instance = OldObj()
>>> type(old_instance)
<type 'instance'>
>>> new_instance = NewObj()
>>> type(new_instance)
<class '__main__.NewObj'>
Inheritance
For classic classes, the search is depth-first, left-to-right in
the order of occurrence in the base class list
For new-style classes, search in an mro order
What's New?
1. MRO
2. property
3. classmethod / staticmethod
4. descriptor (not a decorator)
5. super
6. __new__ and __metaclass__
MRO
Method Resolution Order
It is the order that a new-style class
uses to search for methods and attributes.
Diamond Problem
In classic inheritance, the search order is
FoanPad -> Foan -> TouchScreenDevice -> Pad
That is to say, FoanPad.screen_size = 4
class TouchScreenDevice:
screen_size = 4
class Foan(TouchScreenDevice):
def make_call(self, number):
print "Call " + number
class Pad(TouchScreenDevice):
screen_size = 7
class FoanPad(Foan, Pad):
pass
C3 linearization
The implementation of MRO in python
The right class is next to the left class.
The parent class is next to the child class
Example
1. FoanPad -> Foan -> Pad
2. Foan -> TouchScreen
3. Pad -> TouchScreen
4. FoanPad -> Foan -> Pad ->
TouchScreen
>>> FoanPad.mro()
[<class '__main__.FoanPad'>, <class '__main__.Foan'>, <class '__main__.Pad
object'>]
property
A implementation of get / set function in OO
Example
class Student(object):
def __init__(self, first_name, last_name):
self.first_name = first_name
self.last_name = last_name
def get_name(self):
return self.first_name + " " + self.last_name
def set_name(self, first_name):
self.first_name = first_name
name = property(get_name, set_name)
>>> me = Student("Jim", "Yeh")
>>> me.name
'Jim Yeh'
>>> me.name = Joe
>>> me.name
'Joe Yeh'
classmethod
A implementation of the overloading-like feature in C++
Example
class Host(object):
def __init__(self, name, os):
self.name = name
self.os = os
def _from_linux(cls, name):
return cls(name, "linux")
from_linux = classmethod(_from_linux)
>>> h = Host.from_linux("My Server")
>>> h.os
staticmethod
An isolated function
Example
class Host(object):
def __init__(self, name, os):
self._name = name
self._os = os
def _version():
return "1.0.0"
version = staticmethod(version)
>>> h = Host("My Host", "Linux")
>>> h.version()
Before get into descriptor
The lookup chain of attribute/method
1. __getattribute__
2. __dict__
3. descriptor
4. __getattr__
5. AttibuteError
Classic lookup chain
New Mechanism in New-style class
__getattribute__ only work in new-style class
A descriptor class
It is the mechanism behind properties, methods, static
methods, class methods, function, and super.
Descriptor Protocol
They are three specific methods.
Definition
If any of the methods in the descriptor protocol are defined
for a class, its instance is said to be a descriptor object.
Descriptor.__get__(self, obj, type=None) --> value
Descriptor.__set__(self, obj, value) --> None
Descriptor.__delete__(self, obj) --> None
Example
class MyDescriptor(object):
def __init__(self):
self.val = "Init"
def __get__(self, obj, type=None):
return self.val
def __set__(self, obj, val):
if type(val) != str:
raise TypeError("The value must be a string.")
self.val = "The value I assigned to the variable is: %s" % val
def __delete__(self, obj):
self.val = None
Special cases
data descriptor
An object which defines both __get__ and __set__ function.
non-data descriptor
An object which only define __get__ function.
How to use Descriptor class
Basic Usage
class MyCls(object):
my_desc = MyDescriptor()
>>> inst = MyCls()
>>> print inst.my_desc
'Init'
How it works?
What happens when an instance method is called?
We know
>>> MyCls.__dict__
dict_proxy({'my_desc': <__main__.MyDescriptor object at 0x1078b9c50>})
When you invoke
>>> inst.my_desc
According to , its "__get__" function is invoked.
>>> MyCls.__dict__["my_desc"].__get__(inst, MyCls)
the lookup chain
Caveats
The mechanism of descriptor object won't work if you
assign it on an instance.
A non-data descriptor will be replaced by attribute
assignment.
Built-in descriptors
1. property
2. staticmethod / classmethod
3. functions
4. super
functions
There is an implict function class
Besides, every function is a non-data descriptor class
>>> func = lambda x: x
>>> type(func)
<type 'function'>
>>> func.__get__
<method-wrapper '__get__' of function object at 0x1078a17d0>
>>> func.__set__
Traceback (most recent call last):
AttributeError: 'function' object has no attribute '__set__'
Function(method) in a class
Invoke by instance
class FuncTestCls(object):
def test(self):
print "test"
>>> print type(FuncTestCls.__dict__['test'])
<type 'function'>
As you can see, it's a function.
As we have seen before,
>>> inst = FuncTestCls()
>>> inst.test
>>> FuncTestCls.__dict__['test'].__get__(inst, FuncTestCls)
<bound method FuncTestCls.test of <__main__.FuncTestCls object at 0x10790b9d0
__call__
The place where a function context is put into.
def func(x, y):
return x + y
>>> func.__call__(1, 2)
>>> 3
partial function
import functools
def func(a, b, c):
print a, b, c
partial_func = functools.partial(func, "I am Jim.",)
>>> partial_func("Hey!", "Ha!")
I am Jim. Hey! Ha!
__get__ function in function class
It returns a partial function whose first argument, known as
self, is replaced with the instance object.
Let's review the .
PSEUDO CODE
import functools
def __get__(self, instance, cls):
return functools.partial(self.__call__, instance)
example
Additional usage
By the fact that a function is a descriptor object, every
function can be invoked by an instance.
def inst_func(self):
print self
class MyCls(object): pass
>>> print inst_func.__get__(MyCls(), MyCls)
<bound method MyCls.inst_func of <__main__.MyCls object >>
Bound / Unbound
A function is said to be a bound method if its first variable is
replaced by instance/class through __get__ function.
Otherwise, it is an unbound method.
Example - Bound method
>>> class C(object):
... def test(self):
... print "ttest"
>>> c = C()
>>> c.test
<bound method C.test of <__main__.C object at 0x10cf5a6d0>>
What is super
super is a function which returns a proxy object that
delegates method calls to a parent or sibling class(according
to MRO).
Basic usage of super
Consider the following example:
class A(object):
attr = 1
def method(self):
print "I am A"
class B(A):
attr = 1
def method(self):
super(B, self).method()
print "I am B"
>>> b = B()
>>> b.method()
I am A
I am B
Fact
super is a kind of class
>>> sup_B = super(B)
>>> type(sup_B)
<type 'super'>
super is not a parent class
>>> A == super(B)
False
You have to delegate a target to super before you use it
>>> sup_B = super(B)
>>> sup_B.method
Traceback (most recent call last):
AttributeError: 'super' object has no attribute 'method'
super doesn't know who you want to delegate.
Try this:
>>> super(B, b).method
<bound method B.method of <__main__.B object at 0x105d84990>>
Again, what is super?
Actually, it is a descriptor object.
What super(B, b) does is super(B).__get__(b)
>>> proxy_b = sup_B.__get__(b)
>>> proxy_b.method
<bound method B.method of <__main__.B object>>
Conclude of super
super(B) != A
super(B, b) != super(B).__get__(b)
super(B, b).method == super(B).__get__(b).method
Q & A

Mais conteúdo relacionado

Mais procurados

Descriptor Protocol
Descriptor ProtocolDescriptor Protocol
Descriptor Protocol
rocketcircus
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
lykado0dles
 

Mais procurados (20)

Unit 4 exceptions and threads
Unit 4 exceptions and threadsUnit 4 exceptions and threads
Unit 4 exceptions and threads
 
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونیاسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
اسلاید جلسه ۹ کلاس پایتون برای هکر های قانونی
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Java Programming - 04 object oriented in java
Java Programming - 04 object oriented in javaJava Programming - 04 object oriented in java
Java Programming - 04 object oriented in java
 
Java class
Java classJava class
Java class
 
Descriptor Protocol
Descriptor ProtocolDescriptor Protocol
Descriptor Protocol
 
Classes & objects new
Classes & objects newClasses & objects new
Classes & objects new
 
C# Summer course - Lecture 3
C# Summer course - Lecture 3C# Summer course - Lecture 3
C# Summer course - Lecture 3
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리
 
Csharp_Chap03
Csharp_Chap03Csharp_Chap03
Csharp_Chap03
 
Spsl v unit - final
Spsl v unit - finalSpsl v unit - final
Spsl v unit - final
 
Scala Paradigms
Scala ParadigmsScala Paradigms
Scala Paradigms
 
09. haskell Context
09. haskell Context09. haskell Context
09. haskell Context
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
Java Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and PitfallsJava Generics Introduction - Syntax Advantages and Pitfalls
Java Generics Introduction - Syntax Advantages and Pitfalls
 
Java Tutorials
Java Tutorials Java Tutorials
Java Tutorials
 
Ios development
Ios developmentIos development
Ios development
 
Chapter 2 - Getting Started with Java
Chapter 2 - Getting Started with JavaChapter 2 - Getting Started with Java
Chapter 2 - Getting Started with Java
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Java tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry LevelJava tutorial for Beginners and Entry Level
Java tutorial for Beginners and Entry Level
 

Destaque

Destaque (20)

Faster Python, FOSDEM
Faster Python, FOSDEMFaster Python, FOSDEM
Faster Python, FOSDEM
 
Python on Rails 2014
Python on Rails 2014Python on Rails 2014
Python on Rails 2014
 
Python class
Python classPython class
Python class
 
A deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio moduleA deep dive into PEP-3156 and the new asyncio module
A deep dive into PEP-3156 and the new asyncio module
 
The future of async i/o in Python
The future of async i/o in PythonThe future of async i/o in Python
The future of async i/o in Python
 
Python, do you even async?
Python, do you even async?Python, do you even async?
Python, do you even async?
 
Comandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocerComandos para ubuntu 400 que debes conocer
Comandos para ubuntu 400 que debes conocer
 
Python master class 3
Python master class 3Python master class 3
Python master class 3
 
Python Async IO Horizon
Python Async IO HorizonPython Async IO Horizon
Python Async IO Horizon
 
Practical continuous quality gates for development process
Practical continuous quality gates for development processPractical continuous quality gates for development process
Practical continuous quality gates for development process
 
Async Tasks with Django Channels
Async Tasks with Django ChannelsAsync Tasks with Django Channels
Async Tasks with Django Channels
 
Async programming and python
Async programming and pythonAsync programming and python
Async programming and python
 
The Awesome Python Class Part-4
The Awesome Python Class Part-4The Awesome Python Class Part-4
The Awesome Python Class Part-4
 
Regexp
RegexpRegexp
Regexp
 
What is the best full text search engine for Python?
What is the best full text search engine for Python?What is the best full text search engine for Python?
What is the best full text search engine for Python?
 
Python as number crunching code glue
Python as number crunching code gluePython as number crunching code glue
Python as number crunching code glue
 
Building social network with Neo4j and Python
Building social network with Neo4j and PythonBuilding social network with Neo4j and Python
Building social network with Neo4j and Python
 
Async Web Frameworks in Python
Async Web Frameworks in PythonAsync Web Frameworks in Python
Async Web Frameworks in Python
 
SylkServer: State of the art RTC application server
SylkServer: State of the art RTC application serverSylkServer: State of the art RTC application server
SylkServer: State of the art RTC application server
 
Escalabilidad horizontal desde las trincheras
Escalabilidad horizontal desde las trincherasEscalabilidad horizontal desde las trincheras
Escalabilidad horizontal desde las trincheras
 

Semelhante a Dive into Python Class

Semelhante a Dive into Python Class (20)

Python3
Python3Python3
Python3
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
 
Introduction to Python - Part Three
Introduction to Python - Part ThreeIntroduction to Python - Part Three
Introduction to Python - Part Three
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
1_7a6f85d03f132dcd9d7592bc4643be1c_MIT6_0001F16_Lec8.pdf
 
About Python
About PythonAbout Python
About Python
 
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYAPYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
PYTHON-Chapter 3-Classes and Object-oriented Programming: MAULIK BORSANIYA
 
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_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
nested_Object as Parameter & Recursion_Later_commamd.pptx
nested_Object as Parameter  & Recursion_Later_commamd.pptxnested_Object as Parameter  & Recursion_Later_commamd.pptx
nested_Object as Parameter & Recursion_Later_commamd.pptx
 
Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods Advanced Python : Static and Class Methods
Advanced Python : Static and Class Methods
 
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
 
Python session 7 by Shan
Python session 7 by ShanPython session 7 by Shan
Python session 7 by Shan
 
Chapter 05 classes and objects
Chapter 05 classes and objectsChapter 05 classes and objects
Chapter 05 classes and objects
 
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
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
 
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
 

Mais de Jim Yeh (6)

Write FB Bot in Python3
Write FB Bot in Python3Write FB Bot in Python3
Write FB Bot in Python3
 
Introduction openstack horizon
Introduction openstack horizonIntroduction openstack horizon
Introduction openstack horizon
 
Web develop in flask
Web develop in flaskWeb develop in flask
Web develop in flask
 
Git tutorial II
Git tutorial IIGit tutorial II
Git tutorial II
 
Git Tutorial I
Git Tutorial IGit Tutorial I
Git Tutorial I
 
Introduction to docker
Introduction to dockerIntroduction to docker
Introduction to docker
 

Último

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Último (20)

Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

Dive into Python Class