Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

Class method types in Python

📅 2020-Sep-23 ⬩ ✍️ Ashwin Nanjappa ⬩ 📚 Archive

There are 3 types of methods that can be created in a class in Python: instance methods, class methods and static methods.

Static method

Class method

Instance method

Here is sample code that uses all three types of methods:

class A:
    X = 23

    def __init__(self):
        self.y = 46

    def instance_foo(self):
        """Instance method."""

        print(dir(self))

        # Member access
        print(self.X)
        print(A.X)
        print(self.y)

        # Method access
        self.instance_foo2()
        self.class_foo()
        A.class_foo()
        self.static_foo()
        A.static_foo()

    def instance_foo2(self):
        return

    @classmethod
    def class_foo(cls):
        """Class method."""

        print(dir(cls))

        # Member access
        print(cls.X)
        print(A.X)

        # Method access
        A.class_foo2()
        A.static_foo()

    @classmethod
    def class_foo2(cls):
        return

    @staticmethod
    def static_foo():
        """Static method."""

        # Member access
        print(A.X)

        # Method access
        A.static_foo2()
        A.class_foo2()

    @staticmethod
    def static_foo2():
        return

# Calling instance method
a = A()
a.instance_foo()

# Calling class method
A.class_foo()
a.class_foo()

# Calling static method
A.static_foo()
a.static_foo()