ClassMethod and StaticMethod

30. ClassMethod and StaticMethod#

30.1. ClassMethod#

30.2. StaticMethod#

StaticMethods are simple regular functions but are within the namespace/scope of the class.

The Static methods are created using the decorator staticmethod.

class StaticMethodExample:
    @staticmethod
    def do_something():
        
  Cell In[1], line 4
    
    ^
SyntaxError: incomplete input
class Anime:
    list_of_animes = []

    def __init__(self, name, characters):
        self.name = name
        self.characters = characters
        Anime.list_of_animes.append(name)

    def introduce(self):  # Instance Method.
        print(
            f"Hey weebs! We are {self.name}. We have awesome characters: {self.characters} πŸ”₯"
        )

    @classmethod
    def show_list_and_count_of_animes(cls):  # Class Method.
        print(
            f"Animes listed are: {cls.list_of_animes} which sums up to {len(cls.list_of_animes)}"
        )

    @staticmethod
    def temp():
        return Anime.list_of_animes, __class__.list_of_animes
a = Anime("one piece", ("luffy",))
b = Anime("naruto", ("naruto",))

Method type

Can modify Class Attribute?

Can modify Method Attribute?

Instance Method

βœ…

βœ…

Class Method

βœ…

❌

Static Method

❌

❌

Note

Don’t curse me saying, Hey! I can still modify class attributes from Static Method. Yes, we can absolutely do it using the class as <ClassName>.<class_attribute>, but we wouldn’t be having class