2

I had a question about the preferred way of calling static and class methods within a class in Python ( >= 2.7).

From this resource Calling method, classmethod, staticmethod in the same Python class, I can understand why it is better to use self over the class name to call static methods. My question is if it is better to use self or type(self) when trying to call static/class methods within a class?

class A:
    pass


class B(A):
    @staticmethod
    def f():
        return 5

    def g_option1(self):
        return type(self).f()

    def g_option2(self)
        return self.f()
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
ueg1990
  • 1,003
  • 2
  • 19
  • 39
  • Better is option2. Best is not to use static methods at all. – wim Oct 01 '19 at 20:08
  • I use 3.x, and there is a difference between classmethod and staticmethod annotations. You should read up on them both – Fallenreaper Oct 01 '19 at 20:09
  • 1
    I don't think I understand your question, because what I thought it was was answered in the question you linked. – glibdud Oct 01 '19 at 20:11
  • @wim If we should not use static methods at all, then what type of methods should we use if we want to keep those methods specific to the class? – ueg1990 Oct 01 '19 at 20:13
  • Because if the "method" doesn't need any information about the instance nor the class, then it may as well be a module level function in the first place. Python is not Java, no need to overcomplicate matters in order to be faithful to Java's datamodel or some OOP ideology. – wim Oct 01 '19 at 20:20
  • @wim I disagree, some classes hold "certain types" of functions as static methods because they all relate to each other, or because it's a logical convinience to import them together – Ofer Sadan Oct 01 '19 at 20:22
  • @OferSadan Such conveniences are already adequately provided by the module namespace. – wim Oct 01 '19 at 20:30

0 Answers0