[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Embedding classes' names

On Tue, Jul 16, 2019 at 10:17 AM DL Neil <PythonList at danceswithmice.info> wrote:
> When used, do you embed a class's name within its own code, as a literal?
> In the thread "super or not super?", the OP asked:
> <<<
>         C1.__init__(self) or
>         super().__init__()
>  >>>
> One of the answers recommended super() [agreed!] in order to avoid
> embedding "C1" into the code. The explanation: in case the name of the
> parent class is ever changed.
> Which is eminently reasonable (remember, the parent class may be in a
> separate file, and thus few "cues" to remember to inspect and amend
> sub-classes' code!)
> So, what about other situations where one might need to access the
> class's own name or that of its/a super-class? eg
> class C2(C1):
>         def __init__(self, fred, barney ):
>                 super().__init__( fred )
>                 self.barney = barney
>         def __repr__( self ):
>                 return f"C2( { self.fred }, { self.barney }"
>                 ### note: 'common practice' of "C2" embedded as constant
> How 'purist' do you go, cf YAGNI?

In the case of __repr__, I would most definitely use
self.__class__.__name__, because that way, a subclass can leave repr
untouched and still get decent behaviour.