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())
4 Respostas
+ 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/
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.
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
0
Thanks, I am still a bit confused probably because i need to read more about this. have a good day