class method : what difference calling from instance or class ? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

class method : what difference calling from instance or class ?

Hi everyone, I have done a quick test and I see one can call the class method from a class or from a class instance. Is there a difference ? Or a reason for that ? (Code below prints the same) all the best class beasts: def __init__(self,size): beasts.size=size @classmethod def description(cls): return 'some wild animals' tiger=beasts('big') #calling classmethod from class print(beasts.description()) #calling class method from instance print(tiger.description())

18th May 2020, 8:13 AM
Pierre
4 Answers
+ 1
Let me elaborate: lets say i have a class Beasts, like yours. when i call the class method, automatically passed to to the method as the cls variable is the Beast class, not an instance of it. if i call an instance method of Beast, the instance that the method is called on is passed. If you are still confused, this should help: https://realpython.com/courses/JUMP_LINK__&&__python__&&__JUMP_LINK-method-types/
18th May 2020, 9:14 AM
Brian R
Brian R - avatar
0
Calling a class method automatically passes the class as the class that the method is called from. Calling an instance method automatically passes the instance of the class that the method is called from.
18th May 2020, 8:34 AM
Brian R
Brian R - avatar
0
Hi Brian, not sure what you mean. Here I don't try (I think) to call an instance method. Both are class methods right ? As I defined it as @classmethod
18th May 2020, 8:41 AM
Pierre
0
Thanks, I am still a bit confused probably because i need to read more about this. have a good day
18th May 2020, 9:49 AM
Pierre