Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass self as the first argument for class methods in python

Tags:

python

I am trying to understand the class methods. From what I have read it looks like for the class methods we have to pass cls as the first argument while defining (Similar to instance methods where we pass the self as the first argument). But I see that even if I pass the self as the first argument for a class method it works. Can someone explain me how this works?

I have seen some usage where they have defined the class as a class method but they still pass self as the first argument instead of cls. I am trying to understand the 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)
>>>
like image 287
Pradeep Avatar asked Nov 28 '14 10:11

Pradeep


2 Answers

The use of self and cls is just a naming convention. You can call them whatever you want (don't though!). As such you're still passing in the class object, you've just named it self, rather than cls.

99.999% of Python programmers will expect you to call them self and cls, also a lot of IDEs will complain if you call them anything but self and cls, so please stick to the convention.

like image 132
Ffisegydd Avatar answered Oct 15 '22 17:10

Ffisegydd


i feel like the last answer only discusses the naming convention of the first parameter without explaining what self evaluates to for what is known as a static method vs a regular 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(a.x())
print(b.x())
print(c.x())
print()
print(a.y())
print(b.y())
print(c.y())

the output is the following:

<__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

notice that the method x called by the 3 objects yields varying hex addresses, meaning that the self object is tied to the instance. the y method shows that self is actually referencing the class itself rather than the instance. that is the difference.

like image 26
tipu Avatar answered Oct 15 '22 16:10

tipu