Can I pass myself as the first argument to class methods in python

I am trying to understand class methods. From what I read, it looks like for class methods we should pass cls as the first argument in the definition (similar to instance methods, where we pass self as the first argument). But I see that even if I pass myself as the first argument to the class method, it works. Can someone explain to me how this works?

I saw some use where they defined the class as a class method, but they still pass themselves as the first argument instead of cls. I am trying to understand usage.

#!/usr/bin/python class A(object): def foo(self,x): print "executing foo(%s,%s)"%(self,x) @classmethod def class_foo(self,x): print "executing class_foo(%s,%s)"%(self,x) >>> A.class_foo(2) executing class_foo(<class '__main__.A'>,2) >>> 
+6
source share
2 answers

It seems to me that the last answer discusses the naming convention of the first parameter without explaining what it evaluates itself for what is known as a static method versus the usual method. take the following example:

 class A(object): def x(self): print(self) @classmethod def y(self): print(self) a = A() b = A() c = A() print(ax()) print(bx()) print(cx()) print() print(ay()) print(by()) print(cy()) 

The conclusion is as follows:

 <__main__.A object at 0x7fc95c4549d0> None <__main__.A object at 0x7fc95c454a10> None <__main__.A object at 0x7fc95c454a50> None () <class '__main__.A'> None <class '__main__.A'> None <class '__main__.A'> None 

note that the x method, called by three objects, gives different hexagonal addresses, which means that the self object is bound to an instance. the y method shows that self actually refers to the class itself, and not to the instance. that is the difference.

+3
source

Using self and cls is just a naming convention. You can call them whatever you want ( though! ). So you are still passing in the class object, you just called it self , not cls .

99.999% of Python programmers expect you to call them self and cls , and many IDEs will complain if you call them anything other than self and cls , so please stick to the convention.

+6
source

Source: https://habr.com/ru/post/978826/


All Articles