The Python Oracle

Can python have class or instance methods that do not have "self" as the first argument?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Hypnotic Orient Looping

--

Chapters
00:00 Question
00:28 Accepted answer (Score 20)
00:59 Answer 2 (Score 3)
01:17 Thank you

--

Full question
https://stackoverflow.com/questions/1432...

Accepted answer links:
[staticmethod]: http://docs.python.org/2/library/functio...
[classmethod]: http://docs.python.org/2/library/functio...

Answer 2 links:
[Static class variables in Python]: https://stackoverflow.com/questions/6864...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #oop #methods

#avk47



ACCEPTED ANSWER

Score 22


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)    



ANSWER 2

Score 3


static methods don't need self, they operate on the class

see a good explanation of static here: Static class variables in Python