Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is what I might do:</p> <pre><code>class SuperClass(object): def __init__(self): if type(self) == SuperClass: raise Exception("&lt;SuperClass&gt; must be subclassed.") # assert(type(self) == SuperClass) class SubClass(SuperClass): def __init__(self): SuperClass.__init__(self) subC = SubClassOne() supC = SuperClass() # This line should throw an exception </code></pre> <p>When run (exception is thrown!):</p> <pre><code>[ 18:32 jon@hozbox ~/so/python ]$ ./preventing-direct-instantiation.py Traceback (most recent call last): File "./preventing-direct-instantiation.py", line 15, in &lt;module&gt; supC = SuperClass() File "./preventing-direct-instantiation.py", line 7, in __init__ raise Exception("&lt;SuperClass&gt; must be subclassed.") Exception: &lt;SuperClass&gt; must be subclassed. </code></pre> <hr> <p>Edit (from comments):</p> <pre><code>[ 20:13 jon@hozbox ~/SO/python ]$ cat preventing-direct-instantiation.py #!/usr/bin/python class SuperClass(object): def __init__(self): if type(self) == SuperClass: raise Exception("&lt;SuperClass&gt; must be subclassed.") class SubClassOne(SuperClass): def __init__(self): SuperClass.__init__(self) class SubSubClass(SubClassOne): def __init__(self): SubClassOne.__init__(self) class SubClassTwo(SubClassOne, SuperClass): def __init__(self): SubClassOne.__init__(self) SuperClass.__init__(self) subC = SubClassOne() try: supC = SuperClass() except Exception, e: print "FAILED: supC = SuperClass() - %s" % e else: print "SUCCESS: supC = SuperClass()" try: subSubC = SubSubClass() except Exception, e: print "FAILED: subSubC = SubSubClass() - %s" % e else: print "SUCCESS: subSubC = SubSubClass()" try: subC2 = SubClassTwo() except Exception, e: print "FAILED: subC2 = SubClassTwo() - %s" % e else: print "SUCCESS: subC2 = SubClassTwo()" </code></pre> <p>Prints:</p> <pre><code>[ 20:12 jon@hozbox ~/SO/python ]$ ./preventing-direct-instantiation.py FAILED: supC = SuperClass() - &lt;SuperClass&gt; must be subclassed. SUCCESS: subSubC = SubSubClass() SUCCESS: subC2 = SubClassTwo() </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload