Get classes from "self.MyClass" to improve subclassability

Thomas Güttler hv at tbz-pariv.de
Fri Jun 12 08:47:08 EDT 2015


Hi Steven,

I understand your solution. It is correct and works.

But the missing five characters "self." in the upstream code
produces a lot of more lines in the final result.

Regards,
  Thomas Güttler


Am Freitag, 12. Juni 2015 14:24:06 UTC+2 schrieb Steven D'Aprano:
> On Fri, 12 Jun 2015 04:12:52 -0700, Thomas Güttler wrote:
> 
> > Here is a snippet from the argparse module:
> > 
> > {{{
> >     def parse_known_args(self, args=None, namespace=None):
> >         ...
> >         # default Namespace built from parser defaults if namespace is
> >         None:
> >             namespace = Namespace() # < ======= my issue
> > }}}
> > 
> > I subclass from the class of the above snippet.
> > 
> > I would like to use a different Namespace class.
> > 
> > if the above could would use
> > 
> >     namespace = self.Namespace()
> > 
> > it would be very easy for me to inject a different Namespace class.
> 
> Yes it would.
> 
> And here is how you do it, even when the parent class doesn't:
> 
>     class MySubclass(ParentClass):
>         Namespace = Namespace
>         def parse_known_args(self, args=None, namespace=None):
>             if namespace is None:
>                 namespace = self.Namespace()
>             # any other method overriding needed
>             return super().parse_known_args(args, namespace)
> 
> In Python 2, you cannot use super(), you have to explicitly provide the 
> arguments:
> 
>             return super(MySubclass,self).parse_known_args(args,namespace)
> 
> 
> -- 
> Steve




More information about the Python-list mailing list