+2 votes
2 views
in Python by (520 points)
edited by

Can someone please tell me the difference between a function decorated with @staticmethod and one with @classmethod?

2 Answers

0 votes
by (46.1k points)
edited by

You can use a module function instead of a staticmethod, this method is useless in Python as it knows nothing about the class or instance it was called on. It just gets the arguments that were passed.

On the other hand, Classmethod  is useful when we want the method to be a factory for the class as It gets actual class it was called on as first argument, Hence this method gets passed the class that it was called on or the instance it was called on as first argument.

Therefore @classmethod makes a method whose first argument is the class whereas @staticmethod doesn’t have any implicit arguments.

To summon up I am adding an example of both the methods you can try this by your own in Python

@classmethod example:-

class C:

@classmethod

Def f(cls, arg1, arg2, arg3,…….argN):…..

@Staticmethod example

class C:

@staticmethod

Def f(cls, arg1, arg2, arg3,…….argN):…..

Here N denotes all natural No.

0 votes
by (107k points)
  • A static method does not receive a class as the first argument.
  • A static method is a way of inserting a function into a class, while it shows that it does not require access to the class.

Syntax:-class C(object):

    def fun(arg1, arg2, ...):

        ...

returns: a static method for function fun.

  •  Here’s an example of static methods by the following code:-

    def isAdult(age):

        return age > 18 

  • A static method cannot access or modify the class state.
  • Whereas a class method, receive a class as the first argument.

Synatx:-class C(object)

    def fun(cls, arg1, arg2, ...):

                     ....

fun: a function that needs to be converted into a class method

returns: a class method for function.

  • Here’s an example of class methods by the following code:- 

    def dateOfBirth(cls, name, year):

        return cls(name, date.today().year - year) 

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...