Skip to content
Fix Code Error

Difference between staticmethod and classmethod

March 13, 2021 by Code Error
Posted By: Daryl Spitzer

What is the difference between a function decorated with @staticmethod and one decorated with @classmethod?

Solution

Maybe a bit of example code will help: Notice the difference in the call signatures of foo, class_foo and static_foo:

class A(object):
    def foo(self, x):
        print "executing foo(%s, %s)" % (self, x)

    @classmethod
    def class_foo(cls, x):
        print "executing class_foo(%s, %s)" % (cls, x)

    @staticmethod
    def static_foo(x):
        print "executing static_foo(%s)" % x    

a = A()

Below is the usual way an object instance calls a method. The object instance, a, is implicitly passed as the first argument.

a.foo(1)
# executing foo(<__main__.A object at 0xb7dbef0c>,1)

With classmethods, the class of the object instance is implicitly passed as the first argument instead of self.

a.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)

You can also call class_foo using the class. In fact, if you define something to be
a classmethod, it is probably because you intend to call it from the class rather than from a class instance. A.foo(1) would have raised a TypeError, but A.class_foo(1) works just fine:

A.class_foo(1)
# executing class_foo(<class '__main__.A'>,1)

One use people have found for class methods is to create inheritable alternative constructors.


With staticmethods, neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class:

a.static_foo(1)
# executing static_foo(1)

A.static_foo('hi')
# executing static_foo(hi)

Staticmethods are used to group functions which have some logical connection with a class to the class.


foo is just a function, but when you call a.foo you don’t just get the function,
you get a “partially applied” version of the function with the object instance a bound as the first argument to the function. foo expects 2 arguments, while a.foo only expects 1 argument.

a is bound to foo. That is what is meant by the term “bound” below:

print(a.foo)
# <bound method A.foo of <__main__.A object at 0xb7d52f0c>>

With a.class_foo, a is not bound to class_foo, rather the class A is bound to class_foo.

print(a.class_foo)
# <bound method type.class_foo of <class '__main__.A'>>

Here, with a staticmethod, even though it is a method, a.static_foo just returns
a good ‘ole function with no arguments bound. static_foo expects 1 argument, and
a.static_foo expects 1 argument too.

print(a.static_foo)
# <function static_foo at 0xb7d479cc>

And of course the same thing happens when you call static_foo with the class A instead.

print(A.static_foo)
# <function static_foo at 0xb7d479cc>
Answered By: Anonymous

Related Articles

  • Meaning of @classmethod and @staticmethod for beginner?
  • Creating a singleton in Python
  • Tkinter Custom Rectangle widget
  • How to make a class property?
  • Why does my convolutional model does not learn?
  • Static methods in Python?
  • Multiple context menu in a single qTableView pyqt5
  • Combining pyOSC with pyQT5 / Threading?
  • Trouble understanding behaviour of modified VGG16…
  • How do I programmatically change the parent of a layout
  • Layout doesn't expand more than initial size it was…
  • open telemetry InMemorySpanExporter not reseting…
  • My Button Functions Are Not Working in my Python code
  • Calling class staticmethod within the class body?
  • Matplotlib plot's title is missing for unknown…
  • Usage of __slots__?
  • How to return a negative fraction when subtracting…
  • __init__ and arguments in Python
  • How to monitor a filtered version of a metric in…
  • How not to get a repeated attribute of an object?
  • What does "Fatal error: Unexpectedly found nil while…
  • Adding animation to QPushbutton enterEvent and exitEvent
  • How can I connect a signal to different slots…
  • Python-coded neural network does not learn properly
  • Python is not calling fucntions properly
  • Kivy WebView Error: Cannot add to window, it already…
  • DQN Pytorch Loss keeps increasing
  • Call Class Method From Another Class
  • Pygame Curve Movement Problem How To Fix?
  • QGraphicsItem don't change pen of parent when chaning child
  • How does the @property decorator work in Python?
  • How to use QThread() within class of QWidget function?
  • SVG. Center the text inside tag
  • What does if __name__ == "__main__": do?
  • How to dynamically add widgets to a layout after a…
  • What are the calling conventions for UNIX &…
  • How to move the player across a one background image?
  • Lua inheritance and methods
  • Why do we use __init__ in Python classes?
  • How do Mockito matchers work?
  • Maximum XOR With an Element From Array | Leetcode
  • Specify helper function that's used by another…
  • Callback functions in C++
  • How to split code into different python files
  • pretty-print JSON using JavaScript
  • Why Do I get a Stack Overflow error when using…
  • How can I wrap all BeautifulSoup existing…
  • How do I create a radio button that accept user input text?
  • Backgrid filter not working in backbone app
  • Resizing an image in an HTML5 canvas
  • Start a Thread Timer directly
  • Ukkonen's suffix tree algorithm in plain English
  • ROS topic is not published yet
  • Call a method from a method of another class (Nested Class)
  • Is it better to import static or dynamic with I/O…
  • Passing variables, creating instances, self, The…
  • How to get the updated entry string from a toplevel…
  • How to store the last checked item as default, when…
  • What is The Rule of Three?
  • Django - update inline formset not updating
  • Elegant ways to support equivalence ("equality") in…
  • Tkinter understanding mainloop
  • Create a Custom Widget with QListWidget,QLable and…
  • Unknown difference between logic of OOP code…
  • Correct way of using classes with Python asyncio
  • Understanding the main method of python
  • Custom Id in Django Models
  • Why doesn't my scrolbar appear after clicking the…
  • PyQT5: how to automatically align the widget in QGridLayout?
  • Django 2.2 cannot serialize default values once…
  • How does Python's super() work with multiple inheritance?
  • TensorFlow 2.0 : ValueError - No Gradients Provided…
  • Smart way to truncate long strings
  • Pointers in Python?
  • TypeError: Cannot convert a symbolic Keras…
  • Implement LRU cache with using…
  • wxpython do action before closing wx.EVT_CLOSE
  • Why do Python classes inherit object?
  • iOS UICollectionViewCell resizable dashed border
  • Tkinter example code for multiple windows, why won't…
  • Call constructor of type parameter in generic class
  • How to iterate tuples passed as *args to a class method?
  • Donut piechart in mplcanvas
  • What's the difference between eval, exec, and compile?
  • Are static class variables possible in Python?
  • Why is UICollectionViewDiffableDataSource reloading…
  • How to obtain the Minimum Size/Fixed Size of the…
  • Django testing custom signal arguments with…
  • Python - Instantiating a class without assigning a…
  • TypeError: 'bool' object is not callable
  • Moving cursor to first entry box pyqt5
  • For-each over an array in JavaScript
  • ImportError: No module named dateutil.parser
  • Make a Python function subscriptable
  • Make the whole gridLayoutWidget clickable
  • PyQt5 add text over browser page
  • The result is not as intended, the output is a bound…
  • I am making a browser In pyqt5, but I don't know how…
  • Issues with updating an inventory in Python Code
  • Calculating a number from items in an array then…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How can I parse a JSON file with PHP?

Next Post:

Changing image size in Markdown

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error