Can I pass self as the first argument for class methods in python
python
Solution
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.
Problem
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) >>> ```