[Tutor] a class that may not be instantiated

Albert-Jan Roskam sjeik_appie at hotmail.com
Wed Nov 25 10:51:59 EST 2015


 Hi all,
 
Thanks a lot for your replies!
 
> Date: Wed, 25 Nov 2015 05:19:57 +1100
> From: steve at pearwood.info
> To: tutor at python.org
> Subject: Re: [Tutor] a class that may not be instantiated
> 
> On Tue, Nov 24, 2015 at 03:36:21PM +0000, Albert-Jan Roskam wrote:
> > Hi,
> > 
> > I have two classes with a number of methods that are the same, so I 
> > want to define a super class that holds these methods.
> 
> Sounds like a misuse of classes to me. DRY is not a good reason to make 
> two otherwise unrelated classes subclasses of an otherwise pointless 
> parent.
> 
> Better solutions include:
> 
> - Factor out the common code to a module-level function, and have the 
> classes call that function from their methods:
<snip> > - Use a Mixin class to hold the shared methods, and "mix them in" to the 
> two other classes as needed.
<snip> I think I like this option best. There is as little "visual clutter" in the child classes as possible, but the user does not get confusing info about parent-child relationships.When the methods are converted to functions, one still needs to implement a (very short) method in the child class.But the term "Mixin" is just a convention, right? (Similar to a single leading underscore) It's not that the class name gets mangled whenever it contains the string "Mixin" (similar to name mangling with two leading underscores). > But, let's say you still want to proceed with your first plan:
> 
> 
> > But the super 
> > class (below called _Generic) should not be instantiated, because it 
> > serves no purpose other than the DRY principle. I raise a 
> > NotImplementedError in case if somebody dares to instantiate _Generic.
> 
> Sounds reasonable, although you should be kind to your subclasses:
> 
> class _Generic(object):
>     def __init__(self, *args, **kwargs):
>         if type(self) is _Generic:
>             raise NotImplementedError('abstract base class cannot be instantiated')
> 
> 
> Now your concrete subclasses aren't forced to override __init__ if they 
> don't need to. That "if type"check is a very nice addition indeed. That was also my objection against the use of an abstract method with abc, as Peter mentioned:with abc the __init__ *must* be implemented in the concrete class. Not usually a big problem, but still...  
regards,Albert-Jan 		 	   		  


More information about the Tutor mailing list