0

I understand that static methods are meant to perform operations that do not access methods or attributes within the same class. They simply perform specific operations that do not need the class reference, like building a string with a certain pattern, for example. Class methods, on the other hand, are meant to access methods and attributes of its own class.

However, is there any practical difference between accessing methods/attributes through a @staticmethod or @classmethod? See the two constructions below.

Getting/Setting via @staticmethod

class Foo:

    bar= 1

    @staticmethod
    def set_bar_static(val):
        Foo.bar = val
    
    @staticmethod
    def get_bar_static(val):
        return Foo.bar
    
 

Getting/Setting via @classmethod

class Foo:

    bar= 1

    @classmethod
    def set_bar(cls, val):
        cls.bar= val

    @classmethod
    def get_bar(cls, val):
        return cls.bar
Nicolas Fonteyne
  • 164
  • 3
  • 13
  • 1
    Multiple inheritance could mess things up. – Peter Wood Oct 07 '20 at 15:06
  • How? Could you please expand on that? – Nicolas Fonteyne Oct 07 '20 at 15:09
  • 1
    *Any* inheritance could change the meaning. Your static method refers, well, statically to the class `Foo`. The class method `Foo.set_bar`, called from a subclass of `Foo`, sets an attribute on the calling class, not `Foo`. – chepner Oct 07 '20 at 15:10
  • Thanks! That makes sense @chepner! But if I don't have any inheritance, then these two would behave the same, right? – Nicolas Fonteyne Oct 07 '20 at 15:17
  • Does this answer your question? [Difference between staticmethod and classmethod](https://stackoverflow.com/questions/136097/difference-between-staticmethod-and-classmethod) – Pranav Hosangadi Oct 07 '20 at 15:17
  • 1
    You don't have inheritance *now*. Pretend someone else defined a subclass of `Foo` named `Bar`. Do you think they would want `Bar.set_bar(3)` to set `Foo.bar` or `Bar.bar`? – chepner Oct 07 '20 at 16:00

0 Answers0