Under the classmethod() built-in function in the 2nd chapter itself of the Python Standard Library, I was confused with the two statements, that I’m quoting here: –
A class method receives the class as implicit first argument, just
like an instance method receives the instance.
Ok, till this part I was clear enough, that a classmethod is specific for a class, so, instead of taking self as an implicit argument, which represents an instance of that class, we use cls, which represents the class itself, and binds that classmethod to the class..
Now, here’s another statement later on in this topic which confused me: –
If a class method is called for a derived class, the derived class
object is passed as the implied first argument.
Now, what that is supposed to mean? Is it trying to say that, we actually pass an object to a classmethod when used in this situation? But doesn’t this contradicts the first statement itself.
Can anyone make me understand, how those two statements go hand-in-hand without contradicting each others??
I tried to find out some resource, but couldn’t find an example, demonstrating the second case..
A class is a fully-featured first-class object, just like instances of that class are (though they are obviously not the same objects). When we say a
classmethodofclass Creceives the “class object” as first argument, we say it receives an object which represents a, not an object for whichisinstance(<the object>, C)is true. The latter is called (class) instance, “class object” is reserved for objects which are classes.The second sentence simply clarifies that if the class method is called on a derived class, the class method receives that derived class (AKA “the derived class object”), to enable polymorphic behaviour. For example (Python 3, because f..k old style classes):