SlideShare une entreprise Scribd logo
1  sur  12
Static and Class Methods in
Python
Bhanwar Singh
What?
• It is possible to define two kinds of methods
within a class that can be called without an
instance – static method and class method.
• This feature was introduced to new-style
classes but it can be used for classic classes as
well.
• Normally a class method is passed ‘self’ as its
first argument. Self is an instance object.
• Basically we will modify that behavior i.e.
methods will not expect ‘self’ as first
argument.
But..Why?
• Sometimes we need to process data associated
with classes instead of instances.
• Such as keeping track of instances created or
instances currently in memory. This data is
associated to class.
• Simple function written outside the class can
suffice for this purpose.
• But the code is not well associated with
class, cannot be inherited and the name of the
method is not localized.
• Hence python offers us static and class methods.
What if we try to run a method without self argument?
class Spam(object):
numInstances = 0
def __init__(self):
Spam.numInstances = Spam.numInstances + 1
def printNumInstances():
print("Number of instances created: ", Spam.numInstances)
X = Spam()
Y = Spam()
Spam.printNumInstances()
X.printNumInstances()
But this code shows different behavior for python 2.6 and 3.0
For 2.6 :
None of the method call work.
For 3.0:
Call through class works
Call through instance does not work.
Static Methods
• Simple functions with no self argument.
• Nested inside class.
• Work on class attributes; not on instance
attributes.
• Can be called through both class and instance.
• The built-in function staticmethod()is
used to create them.
How to create?
Class MyClass:
def my_static_method():
………………………………………..
………………………………………..
-------Rest of the code-----------
----------------------------------------
my_static_method = staticmethod(my_static method)
Example
class Spam(object):
numInstances = 0
def __init__(self):
Spam.numInstances = Spam.numInstances + 1
def printNumInstances():
print("Number of instances created: ", Spam.numInstances)
printNumInstances = staticmethod(printNumInstances)
X = Spam()
Y = Spam()
Spam.printNumInstances()
X.printNumInstances()
The output will be –
'Number of instances created: ', 2
'Number of instances created: ', 2
Benefits of Static Methods.
• It localizes the function name in the class
scope (so it won’t clash with other names in
the module).
• It moves the function code closer to where it
is used (inside the class statement).
• It allows subclasses to customize the static
method with inheritance.
• Classes can inherit the static method without
redefining it
Class Methods
• Functions that have first argument as class
name.
• Can be called through both class and instance.
• These are created with classmethod inbuilt
function.
• These always receive the lowest class in an
instance’s tree. (See next example)
How to create?
Class MyClass:
def my_class_method(class_var):
………………………………………..
………………………………………..
-------Rest of the code-----------
----------------------------------------
my_class_method = classmethod(my_class_method)
class A:
hi="Hi! I am in class "
def my_method(cls):
print(A.hi,cls)
my_method = classmethod(my_method)
class B(A):
pass
A.my_method()
B.my_method()
('Hi! I am in class ', <class __main__.A at 0x004A81B8>)
('Hi! I am in class ', <class __main__.B at 0x00540030>)
Output
Example
This behavior of class method make them suitable for data that differs in each
Class hierarchy.
Example
class Spam:
numInstances = 0
def count(cls): # Per-class instance counters
cls.numInstances += 1 # cls is lowest class above instance
def __init__(self):
self.count() # Passes self.__class__ to count
count = classmethod(count)
class Sub(Spam):
numInstances = 0
class Other(Spam): # Inherits __init__
numInstances = 0
x = Spam()
y1, y2 = Sub(), Sub()
z1, z2, z3 = Other(), Other(), Other()
print x.numInstances, y1.numInstances, z1.numInstances
print Spam.numInstances, Sub.numInstances, Other.numInstances
Output
1 2 3
1 2 3

Contenu connexe

Tendances

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 BORSANIYAMaulik Borsaniya
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programmingSrinivas Narasegouda
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods javaPadma Kannan
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in javaHrithikShinde
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oopsHirra Sultan
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python Home
 

Tendances (20)

Types of methods in python
Types of methods in pythonTypes of methods in python
Types of methods in python
 
Python-Encapsulation.pptx
Python-Encapsulation.pptxPython-Encapsulation.pptx
Python-Encapsulation.pptx
 
Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)Chapter2 Encapsulation (Java)
Chapter2 Encapsulation (Java)
 
Python Functions
Python   FunctionsPython   Functions
Python Functions
 
Python - object oriented
Python - object orientedPython - object oriented
Python - object oriented
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
 
Inner classes in java
Inner classes in javaInner classes in java
Inner classes in java
 
Methods in Java
Methods in JavaMethods in Java
Methods in Java
 
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
 
Inheritance In Java
Inheritance In JavaInheritance In Java
Inheritance In Java
 
Object oriented approach in python programming
Object oriented approach in python programmingObject oriented approach in python programming
Object oriented approach in python programming
 
Classes,object and methods java
Classes,object and methods javaClasses,object and methods java
Classes,object and methods java
 
Constructor ppt
Constructor pptConstructor ppt
Constructor ppt
 
Access specifiers(modifiers) in java
Access specifiers(modifiers) in javaAccess specifiers(modifiers) in java
Access specifiers(modifiers) in java
 
Introduction to package in java
Introduction to package in javaIntroduction to package in java
Introduction to package in java
 
Wrapper classes
Wrapper classes Wrapper classes
Wrapper classes
 
Python-DataAbstarction.pptx
Python-DataAbstarction.pptxPython-DataAbstarction.pptx
Python-DataAbstarction.pptx
 
Inheritance in oops
Inheritance in oopsInheritance in oops
Inheritance in oops
 
Polymorphism in Python
Polymorphism in Python Polymorphism in Python
Polymorphism in Python
 
Python programming : Classes objects
Python programming : Classes objectsPython programming : Classes objects
Python programming : Classes objects
 

En vedette

Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in PythonSujith Kumar
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutAudrey Roy
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesMatt Harrison
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners Sujith Kumar
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Paige Bailey
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Thinking hard about_python
Thinking hard about_pythonThinking hard about_python
Thinking hard about_pythonDaniel Greenfeld
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in PythonSujith Kumar
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python amiable_indian
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumarSujith Kumar
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming LanguageLaxman Puri
 
Python PPT
Python PPTPython PPT
Python PPTEdureka!
 
PyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating DecoratorsPyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating DecoratorsGraham Dumpleton
 
Pycon Australia 2011 Keynote - Audrey Roy
Pycon Australia 2011 Keynote - Audrey RoyPycon Australia 2011 Keynote - Audrey Roy
Pycon Australia 2011 Keynote - Audrey RoyAudrey Roy
 
Amazing Things: Third-Party Python Package Ecosystems
Amazing Things: Third-Party Python Package EcosystemsAmazing Things: Third-Party Python Package Ecosystems
Amazing Things: Third-Party Python Package EcosystemsAudrey Roy
 
Kiwi PyCon 2011 - Audrey Roy Keynote Speech
Kiwi PyCon 2011 - Audrey Roy Keynote SpeechKiwi PyCon 2011 - Audrey Roy Keynote Speech
Kiwi PyCon 2011 - Audrey Roy Keynote SpeechAudrey Roy
 
Django Package Thunderdome by Audrey Roy & Daniel Greenfeld
Django Package Thunderdome by Audrey Roy & Daniel GreenfeldDjango Package Thunderdome by Audrey Roy & Daniel Greenfeld
Django Package Thunderdome by Audrey Roy & Daniel GreenfeldAudrey Roy
 

En vedette (20)

Advance OOP concepts in Python
Advance OOP concepts in PythonAdvance OOP concepts in Python
Advance OOP concepts in Python
 
Python Tricks That You Can't Live Without
Python Tricks That You Can't Live WithoutPython Tricks That You Can't Live Without
Python Tricks That You Can't Live Without
 
Learn 90% of Python in 90 Minutes
Learn 90% of Python in 90 MinutesLearn 90% of Python in 90 Minutes
Learn 90% of Python in 90 Minutes
 
Introduction to python for Beginners
Introduction to python for Beginners Introduction to python for Beginners
Introduction to python for Beginners
 
Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)Python 101: Python for Absolute Beginners (PyTexas 2014)
Python 101: Python for Absolute Beginners (PyTexas 2014)
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Python Worst Practices
Python Worst PracticesPython Worst Practices
Python Worst Practices
 
Thinking hard about_python
Thinking hard about_pythonThinking hard about_python
Thinking hard about_python
 
Object Oriented Programming in Python
Object Oriented Programming in PythonObject Oriented Programming in Python
Object Oriented Programming in Python
 
Introduction to Python
Introduction to Python Introduction to Python
Introduction to Python
 
Python Datatypes by SujithKumar
Python Datatypes by SujithKumarPython Datatypes by SujithKumar
Python Datatypes by SujithKumar
 
Python Programming Language
Python Programming LanguagePython Programming Language
Python Programming Language
 
Python PPT
Python PPTPython PPT
Python PPT
 
Python Presentation
Python PresentationPython Presentation
Python Presentation
 
Lsn02 fundamentals
Lsn02 fundamentalsLsn02 fundamentals
Lsn02 fundamentals
 
PyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating DecoratorsPyCon NZ 2013 - Advanced Methods For Creating Decorators
PyCon NZ 2013 - Advanced Methods For Creating Decorators
 
Pycon Australia 2011 Keynote - Audrey Roy
Pycon Australia 2011 Keynote - Audrey RoyPycon Australia 2011 Keynote - Audrey Roy
Pycon Australia 2011 Keynote - Audrey Roy
 
Amazing Things: Third-Party Python Package Ecosystems
Amazing Things: Third-Party Python Package EcosystemsAmazing Things: Third-Party Python Package Ecosystems
Amazing Things: Third-Party Python Package Ecosystems
 
Kiwi PyCon 2011 - Audrey Roy Keynote Speech
Kiwi PyCon 2011 - Audrey Roy Keynote SpeechKiwi PyCon 2011 - Audrey Roy Keynote Speech
Kiwi PyCon 2011 - Audrey Roy Keynote Speech
 
Django Package Thunderdome by Audrey Roy & Daniel Greenfeld
Django Package Thunderdome by Audrey Roy & Daniel GreenfeldDjango Package Thunderdome by Audrey Roy & Daniel Greenfeld
Django Package Thunderdome by Audrey Roy & Daniel Greenfeld
 

Similaire à Advanced Python : Static and Class Methods

Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Christopher Haupt
 
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
 
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
 
Python_Unit_3.pdf
Python_Unit_3.pdfPython_Unit_3.pdf
Python_Unit_3.pdfalaparthi
 
Python data modelling
Python data modellingPython data modelling
Python data modellingAgeeleshwar K
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsHelen SagayaRaj
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲Mohammad Reza Kamalifard
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rdConnex
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python ClassJim Yeh
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with pythonArslan Arshad
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptxEpsiba1
 
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
 

Similaire à Advanced Python : Static and Class Methods (20)

Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)Metaprogramming Primer (Part 1)
Metaprogramming Primer (Part 1)
 
Python3
Python3Python3
Python3
 
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
 
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
 
Unit - 3.pptx
Unit - 3.pptxUnit - 3.pptx
Unit - 3.pptx
 
Python_Unit_3.pdf
Python_Unit_3.pdfPython_Unit_3.pdf
Python_Unit_3.pdf
 
Python data modelling
Python data modellingPython data modelling
Python data modelling
 
Java As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & AppletsJava As an OOP Language,Exception Handling & Applets
Java As an OOP Language,Exception Handling & Applets
 
python note.pdf
python note.pdfpython note.pdf
python note.pdf
 
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
جلسه هفتم پایتون برای هکر های قانونی دوره مقدماتی پاییز ۹۲
 
Lec4
Lec4Lec4
Lec4
 
Presentation 3rd
Presentation 3rdPresentation 3rd
Presentation 3rd
 
Hemajava
HemajavaHemajava
Hemajava
 
Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
 
Object oriented programming with python
Object oriented programming with pythonObject oriented programming with python
Object oriented programming with python
 
class as the basis.pptx
class as the basis.pptxclass as the basis.pptx
class as the basis.pptx
 
Python classes objects
Python classes objectsPython classes objects
Python classes objects
 
Ruby object model
Ruby object modelRuby object model
Ruby object model
 
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
 

Plus de Bhanwar Singh Meena

Internet Society and Internet Engineering task Force.
Internet Society and Internet Engineering task Force.Internet Society and Internet Engineering task Force.
Internet Society and Internet Engineering task Force.Bhanwar Singh Meena
 
Gate 2014 ECE 3rd Paper Solution
Gate 2014 ECE 3rd Paper SolutionGate 2014 ECE 3rd Paper Solution
Gate 2014 ECE 3rd Paper SolutionBhanwar Singh Meena
 
UWB Antenna for Cogntive Radio Application
UWB Antenna for Cogntive Radio ApplicationUWB Antenna for Cogntive Radio Application
UWB Antenna for Cogntive Radio ApplicationBhanwar Singh Meena
 
Equal Split Wilkinson Power Divider - Project Report
Equal Split Wilkinson Power Divider - Project ReportEqual Split Wilkinson Power Divider - Project Report
Equal Split Wilkinson Power Divider - Project ReportBhanwar Singh Meena
 
Equal Split Wilkinson Power Divider - Project Presentation
Equal Split Wilkinson Power Divider - Project PresentationEqual Split Wilkinson Power Divider - Project Presentation
Equal Split Wilkinson Power Divider - Project PresentationBhanwar Singh Meena
 

Plus de Bhanwar Singh Meena (7)

Internet Society and Internet Engineering task Force.
Internet Society and Internet Engineering task Force.Internet Society and Internet Engineering task Force.
Internet Society and Internet Engineering task Force.
 
Quadrature amplitude modulation
Quadrature amplitude modulationQuadrature amplitude modulation
Quadrature amplitude modulation
 
Gate 2014 ECE 3rd Paper Solution
Gate 2014 ECE 3rd Paper SolutionGate 2014 ECE 3rd Paper Solution
Gate 2014 ECE 3rd Paper Solution
 
Advanced Python : Decorators
Advanced Python : DecoratorsAdvanced Python : Decorators
Advanced Python : Decorators
 
UWB Antenna for Cogntive Radio Application
UWB Antenna for Cogntive Radio ApplicationUWB Antenna for Cogntive Radio Application
UWB Antenna for Cogntive Radio Application
 
Equal Split Wilkinson Power Divider - Project Report
Equal Split Wilkinson Power Divider - Project ReportEqual Split Wilkinson Power Divider - Project Report
Equal Split Wilkinson Power Divider - Project Report
 
Equal Split Wilkinson Power Divider - Project Presentation
Equal Split Wilkinson Power Divider - Project PresentationEqual Split Wilkinson Power Divider - Project Presentation
Equal Split Wilkinson Power Divider - Project Presentation
 

Dernier

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxLoriGlavin3
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentPim van der Noll
 

Dernier (20)

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
The State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptxThe State of Passkeys with FIDO Alliance.pptx
The State of Passkeys with FIDO Alliance.pptx
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native developmentEmixa Mendix Meetup 11 April 2024 about Mendix Native development
Emixa Mendix Meetup 11 April 2024 about Mendix Native development
 

Advanced Python : Static and Class Methods

  • 1. Static and Class Methods in Python Bhanwar Singh
  • 2. What? • It is possible to define two kinds of methods within a class that can be called without an instance – static method and class method. • This feature was introduced to new-style classes but it can be used for classic classes as well. • Normally a class method is passed ‘self’ as its first argument. Self is an instance object. • Basically we will modify that behavior i.e. methods will not expect ‘self’ as first argument.
  • 3. But..Why? • Sometimes we need to process data associated with classes instead of instances. • Such as keeping track of instances created or instances currently in memory. This data is associated to class. • Simple function written outside the class can suffice for this purpose. • But the code is not well associated with class, cannot be inherited and the name of the method is not localized. • Hence python offers us static and class methods.
  • 4. What if we try to run a method without self argument? class Spam(object): numInstances = 0 def __init__(self): Spam.numInstances = Spam.numInstances + 1 def printNumInstances(): print("Number of instances created: ", Spam.numInstances) X = Spam() Y = Spam() Spam.printNumInstances() X.printNumInstances() But this code shows different behavior for python 2.6 and 3.0 For 2.6 : None of the method call work. For 3.0: Call through class works Call through instance does not work.
  • 5. Static Methods • Simple functions with no self argument. • Nested inside class. • Work on class attributes; not on instance attributes. • Can be called through both class and instance. • The built-in function staticmethod()is used to create them.
  • 6. How to create? Class MyClass: def my_static_method(): ……………………………………….. ……………………………………….. -------Rest of the code----------- ---------------------------------------- my_static_method = staticmethod(my_static method)
  • 7. Example class Spam(object): numInstances = 0 def __init__(self): Spam.numInstances = Spam.numInstances + 1 def printNumInstances(): print("Number of instances created: ", Spam.numInstances) printNumInstances = staticmethod(printNumInstances) X = Spam() Y = Spam() Spam.printNumInstances() X.printNumInstances() The output will be – 'Number of instances created: ', 2 'Number of instances created: ', 2
  • 8. Benefits of Static Methods. • It localizes the function name in the class scope (so it won’t clash with other names in the module). • It moves the function code closer to where it is used (inside the class statement). • It allows subclasses to customize the static method with inheritance. • Classes can inherit the static method without redefining it
  • 9. Class Methods • Functions that have first argument as class name. • Can be called through both class and instance. • These are created with classmethod inbuilt function. • These always receive the lowest class in an instance’s tree. (See next example)
  • 10. How to create? Class MyClass: def my_class_method(class_var): ……………………………………….. ……………………………………….. -------Rest of the code----------- ---------------------------------------- my_class_method = classmethod(my_class_method)
  • 11. class A: hi="Hi! I am in class " def my_method(cls): print(A.hi,cls) my_method = classmethod(my_method) class B(A): pass A.my_method() B.my_method() ('Hi! I am in class ', <class __main__.A at 0x004A81B8>) ('Hi! I am in class ', <class __main__.B at 0x00540030>) Output Example This behavior of class method make them suitable for data that differs in each Class hierarchy.
  • 12. Example class Spam: numInstances = 0 def count(cls): # Per-class instance counters cls.numInstances += 1 # cls is lowest class above instance def __init__(self): self.count() # Passes self.__class__ to count count = classmethod(count) class Sub(Spam): numInstances = 0 class Other(Spam): # Inherits __init__ numInstances = 0 x = Spam() y1, y2 = Sub(), Sub() z1, z2, z3 = Other(), Other(), Other() print x.numInstances, y1.numInstances, z1.numInstances print Spam.numInstances, Sub.numInstances, Other.numInstances Output 1 2 3 1 2 3