staticmethod vs classmethod python 1

staticmethod vs classmethod python

# With classmethods, the class of the object instance is
# implicitly passed as the first argument instead of self.

class A(object):
    def foo(self, x):
        print(f"executing foo({self}, {x})")

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

    def static_foo(x):
        print(f"executing static_foo({x})")

a = A()

Here is what the above code is Doing:
1. foo() is a regular instance method. It takes self as the first argument.
2. class_foo() is a class method. It takes cls as the first argument instead of self.
3. static_foo() is a static method. It doesn’t take any special first argument.

Similar Posts