python - Raise error if initiating a class, but not when initiating its subclasses -


i'm implementing guess similar abstract class in python. here's example:

in [12]: class a(object):    ....:     def __init__(self, b):    ....:         self.b = b    ....:         raise runtimeerror('cannot create instance of class')    ....:  in [13]: class b(a):    ....:     pass    ....:  in [14]: c=b(2) 

what want example, able initiate b subclass, call c.b , retrieve 2. if call class, give me runtimeerror. problem implementation raise error on b well. how can around this?

one solution, commented, place self.b = b part in subclass , overwrite __init__ function. prefer leave code in superclass if possible, since duplicated quite in quite few subclasses otherwise.

thanks.

import abc  class a(object):     __metaclass__ = abc.abcmeta     @abc.abstractmethod     def __init__(self, b):         pass  class b(a):     def __init__(self, b):         self.b = b  c = a(2) 

Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

javascript - Using Windows Media Player as video fallback for video tag -

c# - Unity IoC Lifetime per HttpRequest for UserStore -