Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
3 views
in Python by (3.4k points)
edited by

Can someone please tell me the basic difference between @classmethod and @staticmmethod, I am good with C++ so you can answer with it's reference too.

As of now, I only know that @classmethod is used to inherit into sub classes and tells about a class. But I don't know what's the use of that? Why can't we just define a class method without adding any @ attributes like @classmethod or @staticmethod.

And when should we use tl;dr:? and why do we use them? and How can we use them?

2 Answers

0 votes
by (46k 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.

Hope this helps, Cheers.

0 votes
by (106k points)

@classmethod means: when this method is called, we pass the class as the first argument instead of the instance of that class (as we normally do with methods). This means you can use the class and its properties inside that method rather than a particular instance.

@staticmethod means: when this method is called, we don't pass an instance of the class to it (as we normally do with methods). This means you can put a function inside a class but you can't access the instance of that class (this is useful when your method does not use the instance).

You can use the following video tutorials to clear all your doubts:-

Related questions

+2 votes
2 answers
asked May 25, 2019 in Python by Krishna (2.6k points)
0 votes
1 answer
asked Oct 8, 2019 in Python by Sammy (47.6k points)

Browse Categories

...