I definitely understand the difference between instance methods and class/static methods in Python. Sometimes you don't want an actual instance of an object to perform some operations. Maybe it's getting certain information that's stored across all instances. However, I can not for the life of me understand the difference between class and static methods.
I understand that class methods take a class argument (usually cls
) and that refers to the current class. Then static methods don't need to take any arguments. However, the only main difference I've seen online is that class methods have access to read/change "class states". I cannot find a good explanation on what a "class state" is.
Here is some code I ran with the output below.
class Person:
SPECIES = "homo sapien"
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} is {self.age} years old"
def get_species(self):
print(f"species: {Person.SPECIES}")
def change_species_instance_method(self):
Person.SPECIES="homo sapien (instance)"
@classmethod
def change_species_class_method(cls):
cls.SPECIES="homo sapien (class)"
@staticmethod
def change_species_static_method():
Person.SPECIES="homo sapien (static)"
me = Person("Kevin", 20)
sam = Person("Sam", 20)
me.get_species()
sam.get_species()
me.change_species_instance_method()
print()
me.get_species()
sam.get_species()
me.change_species_class_method()
print()
me.get_species()
sam.get_species()
me.change_species_static_method()
print()
me.get_species()
sam.get_species()
OUTPUT
species: homo sapien
species: homo sapien
species: homo sapien (instance)
species: homo sapien (instance)
species: homo sapien (class)
species: homo sapien (class)
species: homo sapien (static)
species: homo sapien (static)
So, if both class and static methods can modify class variables (SPECIES in this case), then what is the difference between them, apart from the definition of class methods requiring cls
? Thank you!
Also, another difference people have said is that class methods are used to create new instances of the class, but I've been able to do that with static too. So for something in the relative complexity of the code I'm writing (i.e. so no class inheritance) is there any functional difference between static and class methods?