[Tutor] a class that may not be instantiated

Albert-Jan Roskam sjeik_appie at hotmail.com
Tue Nov 24 10:36:21 EST 2015


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. 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?

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


Thank you!


Albert-Jan
 		 	   		  


More information about the Tutor mailing list