[Tutor] a class that may not be instantiated

Peter Otten __peter__ at web.de
Tue Nov 24 11:31:44 EST 2015


Albert-Jan Roskam wrote:

> 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. 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. Below, only one common method is 
defined in_Generic, namely __repr__ (the other ones are __enter__ and 
__exit__, maybe more, if you must know). At first I thought I'd need the abc 
module for this, but this seems to do the trick. I do not want to enforce 
concrete implementations of abstract methods, which is the goal of abc. Is 
this the way to do this, or this this quirky code?

I think this is OK, but I don't understand your argument against

# python 2
class _Generic:
    __metaclass__ = abc.ABCMeta
    
    @abc.abstractmethod
    def __init__(self, *args, **kwargs):
        pass

either.


> import inspect
> 
> class _Generic(object):
> 
>     def __init__(self, *args, **kwargs):
>         raise NotImplementedError
> 
>     def __repr__(self):
>         fmt = []
>         for arg in inspect.getargspec(self.__init__).args[1:]:
>             value = getattr(self, arg)
>             sr = "%r" if isinstance(value, basestring) else "%s"
>             fmt.append(("%s=" + sr) % (arg, value))
>         return self.__class__.__name__ + "(" + ", ".join(fmt) + ")" 
>         
> class Concrete(Generic):
> 
>     def __init__(self, x=42, y='a'):
>         self.x = x
>         self.y = y
>     
> class OneMore(Generic):
> 
>     def __init__(self, w=555, z='foo'):
>         self.w = w
>         self.z = z
> 
>     
> c = Concrete()
> print repr(c)
> 
> a = _Generic(666)   #  NotImplementedError




More information about the Tutor mailing list