Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does 'self' refer to in a @classmethod?

Tags:

I thought I was starting to get a grip on "the Python way" of programming. Methods of a class accept self as the first parameter to refer to the instance of the class whose context the method is being called in. The @classmethod decorator refers to a method whose functionality is associated with the class, but which doesn't reference a specific instance.

So, what does the first parameter of a @classmethod (canonically 'self') refer to if the method is meant to be called without an instance reference?

like image 527
Yes - that Jake. Avatar asked Feb 10 '09 17:02

Yes - that Jake.


People also ask

What does self mean in a Python function?

The self keyword is used to represent an instance (object) of the given class. In this case, the two Cat objects cat1 and cat2 have their own name and age attributes. If there was no self argument, the same class couldn't hold the information for both these objects.

What is self and CLS in Python?

self vs clsThe difference between the keywords self and cls reside only in the method type. If the created method is an instance method then the reserved word self has to be used, but if the method is a class method then the keyword cls must be used.

Where do we use self in Python?

The self is used to represent the instance of the class. With this keyword, you can access the attributes and methods of the class in python. It binds the attributes with the given arguments. The reason why we use self is that Python does not use the '@' syntax to refer to instance attributes.

What does return self do in Python?

return self would return the object that the method was called from.


1 Answers

class itself:

A class method receives the class as implicit first argument, just like an instance method receives the instance.

class C:     @classmethod     def f(cls):         print(cls.__name__, type(cls))  >>> C.f() C <class 'type'> 

and it's cls canonically, btw

like image 72
SilentGhost Avatar answered Oct 09 '22 01:10

SilentGhost