Can python have class or instance methods that do not have "self" as the first argument?
Question:
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?
Answers:
static methods don’t need self, they operate on the class
see a good explanation of static here:
Static class variables in Python
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)
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?
static methods don’t need self, they operate on the class
see a good explanation of static here:
Static class variables in Python
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)