Class methods are great for writing alternate constructors (Say, parsing a particular data format). Static methods can be used for class-specific utils that don't operate on a class instance. Answer from TouchingTheVodka on reddit.com
🌐
Reddit
reddit.com › r/learnpython › class & static methods
r/learnpython on Reddit: CLASS & STATIC METHODS
December 30, 2021 -

Hello everyone,

I was studying OOP and the concept of instances, class methods and static methods still confuses me.

I have watched tons of YouTube already but I can't find a person who explains it as dumb as possible because that is how I understand things.

Please if there is anyone who can recommend to me a video or explain it to me in the simplest way possible with examples, I will be glad :)

Note: I want the simplest form of explanation about the matter.

Top answer
1 of 5
3
Classes for Beginners A lot of beginners struggle to get their heads around classes, but they are pretty much fundamental to object orientated programming. I usually describe them as the programming equal of moulds used in factories as a template for making lots of things that are identical. Imagine pouring molten iron into a mould to make a simple iron pot. You might produce a set of instructions to be sold with the pots that tell the owner how to cook using the pot, how to care for it, etc. The same instructions apply to every pot BUT what owners actually do is entirely up to them. Some might make soup, another person a stew, etc. In Python, a class defines the basics of a possible object and some methods that come with it. (Methods are like functions, but apply to things made using the class.) When we want create a Python object using a class, we call it 'creating an instance of a class'. If you have a class called Room, you would create instances like this: lounge = Room() kitchen = Room() hall = Room() As you typically want to store the main dimensions (height, length, width) of a room, whatever it is used for, it makes sense to define that when the instance is created. You would therefore have a method called __init__ that accepts height, length, width and when you create an instance of Room you would provide that information: lounge = Room(1300, 4000, 2000) The __init__ method is called automatically when you create an instance. It is short for initialise (intialize). You can reference the information using lounge.height and so on. These are attributes of the lounge instance. I provided the measurements in mm but you could include a method (function inside a class) that converts between mm and ft. Thus, I could say something like lounge.height_in_ft(). Methods in classes are usually defined with a first parameter of self: def __init__(self, height, length, width): # code for __init__ def height_in_ft(self): # code to return height The self is a shorthand way of referring to an instance. When you use lounge.height_in_ft() the method knows that any reference to self means the lounge instance, so self.height means lounge.height but you don't have to write the code for each individual instance. Thus kitchen.height_in_ft() and bathroom.height_in_ft() use the same method, but you don't have to pass the height of the instance as the method can reference it using self.height EXAMPLE Room class The code shown as the end of this post will generate the following output: Lounge 1300 4000 4000 Snug 1300 2500 2500 Lounge length in feet: 4.26509187 Snug wall area: 11700000 in sq.mm., 125.94 in sq.ft. Note that a method definition that is preceded by the command, @staticmethod (a decorator) is really just a function that does not include the self reference to the calling instance. It is included in a class definition for convenience and can be called by reference to the class or the instance: Room.mm_to_ft(mm) lounge.mm_to_ft(mm) Here's the code for the full programme: class Room(): def __init__(self, name, height, length, width): self.name = name self.height = height self.length = length self.width = width @staticmethod def mm_to_ft(mm): return mm * 0.0032808399 @staticmethod def sqmm_to_sqft(sqmm): return sqmm * 1.07639e-5 def height_in_ft(self): return Room.mm_to_ft(self.height) def width_in_ft(self): return Room.mm_to_ft(self.width) def length_in_ft(self): return Room.mm_to_ft(self.length) def wall_area(self): return self.length * 2 * self.height + self.width * 2 * self.height lounge = Room('Lounge', 1300, 4000, 2000) snug = Room('Snug', 1300, 2500, 2000) print(lounge.name, lounge.height, lounge.length, lounge.length) print(snug.name, snug.height, snug.length, snug.length) print(lounge.name, 'length in feet:', lounge.height_in_ft()) print(f'{snug.name} wall area: {snug.wall_area()} in sq.mm., ' + \ f'{snug.sqmm_to_sqft(snug.wall_area()):.2f} in sq.ft.') Another useful decorator is @property, which allows you to refer to a method as if it is an attribute. Not used in the example, but if I put that before the height_in_ft methods you could say, for example, lounge.height_in_ft instead of lounge.height_in_ft(). One can write classes that are based on other classes. These child classes inherit all of the characteristics of the parent (or super) class but any attribute or method can be overridden to use alternatives that apply only to the child (and its children). Such child classes might have additional methods, alternative __init__ methods, different default output when referenced in a print statement, and so on. The example code code does not demonstrate this feature.
2 of 5
1
THIS VIDEO SEEMS TO BE DEEP IN TO : https://youtu.be/_EljKJHSGis?si=OO2QBUKRe2FNERfM VIST IS
🌐
Reddit
reddit.com › r/learnprogramming › static method vs class method
Static method vs Class method : r/learnprogramming
March 8, 2022 - Class methods are good if you have global state you need to share access to (not usually something you want, but it's sometimes useful), and static methods are good if you need to provide helpful utility functions that don't depend on an instance of a class (eg, if you have a Vector class that ...
🌐
Reddit
reddit.com › r/learnpython › classmethod vs staticmethod
r/learnpython on Reddit: classmethod vs staticmethod
November 1, 2018 -

I looked up static methods in Python and found this little article comparing class methods and static methods. The article states that class methods are designed to change the state of a class rather than an instance of a class. It also states that class methods are good for creating factory methods, and it shows this sample code:

# Python program to demonstrate  
# use of class method and static method. 
from datetime import date 
  
class Person: 
    def __init__(self, name, age): 
        self.name = name 
        self.age = age 
      
    # a class method to create a Person object by birth year. 
    @classmethod
    def fromBirthYear(cls, name, year): 
        return cls(name, date.today().year - year) 
      
    # a static method to check if a Person is adult or not. 
    @staticmethod
    def isAdult(age): 
        return age > 18
  
person1 = Person('mayank', 21) 
person2 = Person.fromBirthYear('mayank', 1996) 
  
print person1.age 
print person2.age 
  
# print the result 
print Person.isAdult(22) 

Is there really a reason to use a class method rather than a static method for the fromBirthYear() method? The only advantage I can see is that the class name does not have to be used inside the method, so that if the class name changes the method does not have to change.

Top answer
1 of 16
4020

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(f"executing foo({self}, {x})")

    @classmethod
    def class_foo(cls, x):
        print(f"executing class_foo({cls}, {x})")

    @staticmethod
    def static_foo(x):
        print(f"executing static_foo({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>
2 of 16
990

A staticmethod is a method that knows nothing about the class or instance it was called on. It just gets the arguments that were passed, no implicit first argument.

A classmethod, on the other hand, is a method that gets passed the class it was called on, or the class of the instance it was called on, as first argument. This is useful when you want the method to be a factory for the class: since it gets the actual class it was called on as first argument, you can always instantiate the right class, even when subclasses are involved. Observe for instance how dict.fromkeys(), a classmethod, returns an instance of the subclass when called on a subclass:

>>> class DictSubclass(dict):
...     def __repr__(self):
...         return "DictSubclass"
... 
>>> dict.fromkeys("abc")
{'a': None, 'c': None, 'b': None}
>>> DictSubclass.fromkeys("abc")
DictSubclass
>>> 
🌐
GeeksforGeeks
geeksforgeeks.org › python › class-method-vs-static-method-python
Class method vs Static method in Python - GeeksforGeeks
4 days ago - A static method is a method that does not receive self or cls automatically. It behaves like a normal function but is placed inside a class because it logically belongs there.
Find elsewhere
🌐
Reddit
reddit.com › r/learnpython › @classmethod -when to use it
r/learnpython on Reddit: @classmethod -When to use it
September 23, 2020 -

Hey, so I am fairly new to python and programming. I came across the decorators \@classmethod and \@staticmethod. I understand the difference between them both, but when do I really use it. As far as I can comprehend, I cannot find reasons why to use them over stand alone functions.

Top answer
1 of 4
7
You would use @classmethod very rarely. The most common use that I can think of is to make alternate constructors for your class. class NihilistNinja: def __init__(self, data, date): self.data = data self.date = date self.all_instances.append(self) @classmethod def from_file(cls, filename): with open(filename) as f: return cls(*json.load(f)) obj = NihilistNinja(42, 24) # normal constructor obj = NihilistNinja.from_file('datafile.json') # alternate constructor @staticmethod is even more rare. I can't think of a good reason to use it over a normal method. Others will tell you to use it when a method does not need self but still logically belongs in a class. IMO that's no reason to not make it a full blown, normal method.
2 of 4
5
Factories are good candidates for @classmethod, e.g. if you want to create an object from different data, e.g. a string, or a list you could: class A: @classmethod def from_list(cls, lst): return cls(lst[0], lst[1]) @classmethod def from_string(cls, s): return cls(*s.split()) E.g. pandas has a number of from_ class methods on DataFrame. Note: in derived classes the cls passed in will be the derived class, so it will create the right type. class B(A): pass B.from_list(lst) # creates a B not an A. @staticmethod is just a normal function and the only reason to have them in a class is because there is such a close relationship between the staticmethod and the class that it provides good coherence and all the class is doing is providing a namespace.
🌐
Reddit
reddit.com › r/learnpython › how to use @classmethod and @staticmethod ?
r/learnpython on Reddit: how to use @classmethod and @staticmethod ?
January 11, 2018 -

For example, I creat a vector class, and I want to calculate the distance between vector 1 and vector 2, it seemed that I should use @classmethod, well, I did not success, and I can use @staticmethod, but I am not sure it is correct. here is my code

class Vector(object):
    def __init__(self,x,y):
        self.x = x
        self.y = y

    @classmethod
    def distance_1(self,cls):
        return (self.x-cls.x)**2 + (self.y-cls.y)**2

    @staticmethod
    def distance_2(self,cls):
        return (self.x-cls.x)**2 + (self.y-cls.y)**2

if __name__ == '__main__':
    a = Vector(1,1)
    print(a.distance_1(Vector(2,2)))
🌐
Reddit
reddit.com › r/learnpython › can someone explain to me static and class method
r/learnpython on Reddit: can someone explain to me static and class method
April 2, 2019 -

i've searched everywhere and gotten some answers but it still doesnt make 100% of sense to me what exactly are the purpose of these two??. any answers given to me is appreciated. please and thank you.

🌐
Medium
medium.com › @ryan_forrester_ › class-methods-vs-static-methods-in-python-a-clear-guide-47fcfd385e27
Class Methods vs Static Methods in Python: A Clear Guide | by ryan | Medium
November 4, 2024 - class Example: class_variable = "I'm shared across all instances" def __init__(self, instance_var): self.instance_var = instance_var @classmethod def class_method(cls): print(f"Class method accessing class variable: {cls.class_variable}") return cls("Created via class method") @staticmethod def static_method(): print("Static method can't access class or instance variables directly") return "Static result" def instance_method(self): print(f"Instance method accessing instance var: {self.instance_var}") # Using the methods example = Example("instance value") # Class method can access class state
🌐
Reddit
reddit.com › r/learnpython › when to use static methods?
r/learnpython on Reddit: When to use static methods?
May 12, 2016 -

I'm writing a class which has a couple of methods that the ide (pycharm) has flagged up could be static methods. I haven't really used these before.

(To confirm is a static method any method that doesn't use any of the objects attributes or methods?)

I'm not sure when a method should be a static method or a seperate function outside the class (or perhaps something else eg normal instance methods).

All of the (possible) static methods are used by other methods within the class.
One of them is used by a method (which calls several of the object methods in a particular sequence) and is used to convert output from one method to another. This feels like it it's definitely tied to the object, but not sure if it should be a static method or an instance method (it will only ever be used on an instance not on the class itself).

Other potential static methods are more like helper functions that I don't need elsewhere than that object but are used by some of the object methods. eg.

 @staticmethod
def log_database_create(instance):
    sys.stdout.write('New {} created \n'.format(instance.__class__.__name__))

@staticmethod
def log_database_update(instance):
    sys.stdout.write('{}: updated \n'.format(instance.__class__.__name__))

@staticmethod
    def make_int(string):
        s = string.strip()
        return int(s) if s else None
🌐
Board Infinity
boardinfinity.com › blog › class-and-static-method-in-python-differences
Class and Static Method in Python: Differences | Board Infinity
January 3, 2025 - A static method in Python means it is a method that belongs to the class. Static methods are class methods and do not have access to attributes on a class or instance of the class at their own instance or to other instances or class attributes.
🌐
Reddit
reddit.com › r/learnpython › why are static methods callable on class instances?
r/learnpython on Reddit: Why are static methods callable on class instances?
November 29, 2023 -

I have been writing python heavily for a good 5 years or so, but I just now realized that this is possible:

class MyClass:
    @staticmethod
    def my_cool_static_func():
        # do static things

    def some_other_func(self):
        # how strange, I can call a static method on a class instance...
        self.my_cool_static_func()

I'm encountering this exact pattern quite a bit in an old codebase for a company I just started working for, and I'm wondering why someone would do this? Why not make both of these static (or use a class method)?

class MyClass:
    @staticmethod
    def my_cool_static_func():
        # do static things

    @staticmethod
    def some_other_func():
        MyClass.my_cool_static_func()

This second example seems a lot more familiar and logical to me coming from other languages. Is there a functional difference between these two? Is there a non-functional reason one might want to (or even should) write the first example over the second? I'm kinda prejudiced against example one; if I see `self.some_func()` I immediately think "ah an instance method that needs instance state", so I don't love the ambiguity created by being able to call a static method this way, but I'd like to understand this first. Why is the first example even possible in python? If its just a byproduct of some internal language design thing, is it actually useful for anything? Should it be avoided?

Top answer
1 of 5
5
Calling it as self.my_cool_static_func allows subclasses to override it. It would also allow an instance to redirect the call if it set a callable instance attribute called my_cool_static_func, but that's certainly not a good pattern. Good practice in general is to avoid static methods (and to use a class method instead if appropriate or just a regular function if not). The "reason" it works at all in Python is that all methods, including instance methods (in their unbound form), are class attributes. The creation of a bound instance method happens dynamically when an attribute access falls through from the instance to its class (or one of the class's superclasses) using something called the descriptor protocol, which the function type implements. Also consider that instance methods would have a hard time accessing the correct version of a class attribute that was changed in a subclass if you couldn't do a lookup via self (and that this applies to methods as well is simply a result of the fact that Python makes to explicit distinction between methods and other types of class attribute). Of course, this doesn't really explain why classes were designed in this way in the first place, though it does certainly break down all typical OOP features to some quite simple mechanisms (nested namespace lookup + descriptor protocol).
2 of 5
2
Talking about differrence, in the first example you can subclass MyClass and override my_cool_static_func(). Then, if in some_other_func you call self.my_cool_static_func() you'll get an overridden one. On the other hand MyClass.my_cool_static_func() always call the method from MyClass, no matter where the call is originated from.
🌐
Reddit
reddit.com › r/python › @staticmethod and @classmethods
r/Python on Reddit: @staticmethod and @classmethods
February 22, 2021 -

I was wondering what would be the benefits of using `@staticmethod` or `@classmethod`.

Decided to measure their execution speed.

Turns out they are slightly slower than module level function and much faster than usual class method:

Difference in speed of execution of different types of methods in Python

  • Without initiating class, when possible:

Method Type time in seconds
function 1.469
method 4.370
class_method 1.869
static_method 1.653
property_method 4.471
  • Initiating classes

Method Type time in seconds
function 1.462
method 4.503
class_method 2.641
static_method 2.379
property_method 4.382

https://github.com/almazkun/methods_speed

🌐
Python Engineer
python-engineer.com › posts › difference-classmethod-and-staticmethod
Difference between @classmethod, @staticmethod, and instance methods in Python. - Python Engineer
Use this when you don't need to access variables that belong to an instance, but still need general attributes that belong to the class. Static methods can neither access class variables/methods nor instance variables/methods.
🌐
DEV Community
dev.to › gaurbprajapati › class-method-vs-static-method-python-oops-3fek
Class Method Vs Static Method Python OOPS - DEV Community
August 15, 2023 - It's a way to interact with the class itself within the context of a class method, providing flexibility and enhanced functionality. Static methods are defined using the @staticmethod decorator.
Top answer
1 of 2
3

If your method calls a static method on the class, then it does require information on the class. You have a class method, not a static method. By declaring it @classmethod (and adding the cls parameter), you not only properly inform the reader, you allow polymorphism. An inheritor can reimplement the called static method and change behavior.

2 of 2
2

Python's static methods are intended for methods that are part of a class, and can be called as either a class method or an instance method: both Class.the_method() and self.the_method() would work. When the static method is called, it is not given an implicit first argument:

class Example:
  def instance_method_example(self, arguments):
    ...

  @classmethod
  def class_method_example(cls, arguments):
    ...

  @staticmethod
  def static_method_example(arguments):
    ...

If you merely want to create a helper function that is used within your class, do not use @staticmethod. Define a free function outside of the class. For example:

class Example:
  def some_method(self, argument):
    return _helper(argument, self.x)

def _helper(a, b):
  ...

The background of static methods in Python is the following: when you access an attribute of an object x.attribute or getattr(x, 'attribute'), then this name is looked up in the instance dict or the class dict. If an object is found in the class dict, it is checked whether that object is a “descriptor”: an object that describes how this attribute behaves, not an object that would be directly returned. Descriptors have dunder-methods like __get__, __set__, and __del__ that are invoked depending on whether the descriptor is accessed, assigned to, or deleted with the del operator.

Functions – the things you declare with def – are descriptors. By default, the __get__ descriptor binds the function to the instance argument (typically called self) and returns the bound function, so that it can be invoked as a method. But the various decorators change this behaviour:

  • a @classmethod def binds to the class object, not the instance
  • a @staticmethod def does not bind to any object and just returns the underlying function directly
  • a @property invokes the underlying function to retrieve a value

These differences are (partially) visible when looking at the repr() of the bound methods. With the first Example class:

  • instance_method_example
    • with class: Example.instance_method_example
      is <function Example.instance_method_example at 0x7f1dfdd6fd30>,
      the unbound function
    • with instance: <function Example.instance_method_example at 0x7f1dfdd6fd30>
      is <bound method Example.instance_method_example of <__main__.Example object at 0x7f1dfdddcb80>>,
      a method bound to the instance
  • class_method_example
    • with class: Example.class_method_example
      is <bound method Example.class_method_example of <class '__main__.Example'>>,
      a method bound to the class
    • with instance: Example().class_method_example
      is <bound method Example.class_method_example of <class '__main__.Example'>>,
      also a method bound to the class
  • static_method_example
    • with class: Example.static_method_example
      is <function Example.static_method_example at 0x7f1dfdd6fe50>,
      the unbound function
    • with instance: Example().static_method_example
      is <function Example.static_method_example at 0x7f1dfdd6fe50>,
      also the unbound function

As a table:

invoked on… no decorator @classmethod @staticmethod
… instance bound to instance bound to class unbound
… class unbound bound to class unbound