LongClassName.static_method() vs __class__.static_method()

Consider the two ways to call a static method in the same class as caller. Is there a difference semantically? Is one preferable over the other?

I find __class__ more expressive and less error prone (copy/paste) but I could well be wrong.

class LongClassName:
  @staticmethod
   def static_method():
     pass
   def __init__() {
     __class__.static_method()
     LongClassName.static_method()
  }

__class__ is an implementation detail that primarily exists to make the no-argument super call function. While it’s documented, I have never seen it being suggest to be used anywhere.

I think you are going to find that many people will be surprised that it works and that it’s very different from self.__class__.

The documentation doesn’t introduce __class__ in the CPython implementation detail section so I would say it’s meant as part of the language.

I personally use it occasionally exactly like the OP does (typos notwithstanding) to refer to the enclosing class without explicitly naming it, to keep the code DRY.

Note to the OP that unless you have good reasons to avoid method override in a subclass, you should typically call self.static_method() instead to allow an override to work.

4 Likes

Thank you for the note on overriding in subclass.

__init__, defined properly, already has a way to access a static method:

class LongClassName:
    @staticmethod
    def static_method():
        pass

    def __init__(self):
        self.static_method()

If you are asking how best to call one static method from another static method, I’d say the first thing to do is to avoid using so many static methods: they really aren’t that common, so in the rare cases where you need to access a static method, you just type out the full name.