5

Occasionally, a class will have a "private" @classmethod which other methods call:

class FooClassThisSometimesHasALongNameEspIfAUnittestSubclasss(...):
    @classmethod
    def foo():
        ... 

    def bar(self):
        ...
        FooClassThisSometimesHasALongNameEspIfAUnittestSubclasss.foo()
        ...

As can be seen, the class name is repeated; it's admittedly probably not serious enough to cause a meltdown of current technology followed by a zombie apocalypse, but it's still a DRY violation, and somewhat annoying.

The answer to a similar question about super stated that this is one of the reasons for the Py3's new super.

In the absence of some magic normal() function (which, as opposed to super(), returns the current class), is there some way to avoid the repetition?

Community
  • 1
  • 1
Ami Tavory
  • 74,578
  • 11
  • 141
  • 185
  • Is there a reason not to do `def bar(self): self.foo(); ...`? You can still call a class method with `self`, but now I'm wondering if this is against some kind of convention? – Marses Aug 18 '23 at 12:45

1 Answers1

2

You could use:

self.__class__.foo()
Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
  • That's very useful, thanks! However, it being so simple, why wasn't this used for ``super``? – Ami Tavory Jun 09 '15 at 21:06
  • @AmiTavory: super() can call parent classes but also sibling classes. It's therefore a different concept from using `self.__class__`. – Simeon Visser Jun 09 '15 at 21:16
  • Thanks, but my question is a bit different and concerns the delta between the old ``super`` and the new one. Your excellent answer implies that DRY should not have really been a consideration, and yet is somehow was. – Ami Tavory Jun 09 '15 at 21:18
  • @AmiTavory: the changes to super() in Python 3.x were indeed made to avoid repeating yourself. I'm not sure how my answer implies DRY should not be a consideration? In principle you could also have written super(self.__class__, self) in Python 2.x but most usage out there tends to repeat the class name. In any case this was a bad thing and that's why changes were made to super(). – Simeon Visser Jun 09 '15 at 21:33
  • or `type(self).foo` if you don't care for all the double-underscoring. – kindall Jun 09 '15 at 22:32
  • @kindall Thanks, that's very useful. – Ami Tavory Jun 10 '15 at 22:27
  • 1
    Actually, since this is a `classmethod`, you can call it on an instance without any trouble as `self.foo`. – kindall Jun 12 '15 at 16:44