Every single example I have seen of a method in a class in Python, has self
as the first argument. Is this true of all methods? If so, couldn't python have been written so that this argument was just understood and therefore not needed?
Asked
Active
Viewed 1.0k times
7

Karl Knechtel
- 62,466
- 11
- 102
- 153

bob.sacamento
- 6,283
- 10
- 56
- 115
-
1and [What is the advantage of having this/self pointer mandatory explicit?](http://stackoverflow.com/q/910020) – Martijn Pieters Jan 14 '13 at 22:20
-
instance methods are passed the instance as first argument, class methods the class – Facundo Casco Jan 14 '13 at 22:21
-
3Based on one of the existing answers, this question isn't a 100% duplicate. I'm voting to reopen. – Mark Ransom Jan 14 '13 at 22:27
-
Certainly sounds like a duplicate, granted, but the answers to that other question really aren't getting at my question, with the exception of one answer that links to Guido's blog, and I can't read that to confirm right now because of a firewall problem. – bob.sacamento Jan 14 '13 at 22:30
2 Answers
21
If you want a method that doesn't need to access self
, use staticmethod
:
class C(object):
def my_regular_method(self, foo, bar):
pass
@staticmethod
def my_static_method(foo, bar):
pass
c = C()
c.my_regular_method(1, 2)
c.my_static_method(1, 2)
If you want access to the class, but not to the instance, use classmethod
:
class C(object):
@classmethod
def my_class_method(cls, foo, bar):
pass
c.my_class_method(1, 2)

abarnert
- 354,177
- 51
- 601
- 671
3
static methods don't need self, they operate on the class
see a good explanation of static here: Static class variables in Python
-
3Static methods don't operate on the class; they have no reference to the class other than the class name itself. – Ignacio Vazquez-Abrams Jan 14 '13 at 22:23