+ 2

What is the difference between these functions?

I am trying to understand static methods for classes in Python. class B: def hey(): print("hey") class B: @classmethod def hey(cls): print("hey") Both function produce the same result. What is the difference?

31st May 2018, 9:00 AM
Yusuf
Yusuf - avatar
6 Answers
+ 5
Based on my idiotic understandings: The first one can only invoked through the Instance of that Class. The second one can be invoked through the Class itself and the Instance of that Class. What makes 'classmethods' unique in my opinion is that the method can access the class because of the first parameter (cls). Here's a bad example of mine: https://code.sololearn.com/clh3339oqTLn/?ref=app If you want to have a plain static function (no 'self' or 'cls'), use '@staticmethod'
31st May 2018, 9:39 AM
luʁi
+ 2
You will understand the difference when you make those methods use instance variables.
31st May 2018, 12:57 PM
Mitali
Mitali - avatar
+ 1
The first one can be invoked through the Class itself. https://code.sololearn.com/c0LF9COaDSHC/?ref=app
31st May 2018, 10:48 AM
Yusuf
Yusuf - avatar
+ 1
There are two types of methods .Instance methods(what is in example 1) which take self as the first argument.They are associated with objects and use instance variables. But static methods dont need self to be their first argument as they are associated to class not to the objects and use no instance variables.
31st May 2018, 12:47 PM
Mitali
Mitali - avatar
+ 1
Thank you for explaining. But know that. What I want to learn is why do static and class methods behaves in the same way?
31st May 2018, 12:50 PM
Yusuf
Yusuf - avatar
+ 1
You mean it is a programming experience. But I don't think so. As the man who learns from experience , I can say that anybody who understood a context well could tell the knowledge to others.
31st May 2018, 1:03 PM
Yusuf
Yusuf - avatar