Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>2 Possibilities</p> <p>instead of <code>isinstance(second, A)</code> do <code>isinstance(second.obj, A)</code></p> <p>Second... more hackish way is to do something like this:</p> <pre><code>class B: def __init__(self, obj): self.obj = obj # obj is any object self.__class__ = obj.__class__ </code></pre> <p>This is hackish as it basically fools the interpreter into into thinking the instance is a different class. That is <code>isinstance(second, B)</code> will return <code>False</code></p> <p>To answer the question posed below: the interpreter will basically act as if <code>second</code> is a class <code>A</code> and nothing defined at the class level in <code>B</code> will remain. eg if you do something like</p> <pre><code>class B: b=2 #Won't be visible def __init__(self, obj): self.obj = obj # obj is any object self.b2 = 5 #Instance variable will be visible self.__class__ = obj.__class__ def someFunc(self): #Won't be visible return 3 </code></pre> <p>Using the same code as you used above for initialization here is what will happen with some calls using the interpreter. In general any class variables or methods will be removed and instead use <code>A</code>'a, however any instance variables will be remembered. Because of this doing <code>self.obj = obj</code> is a bit redundant. Basically instantiating <code>B(obj)</code> will more or less return an object of the same class as <code>obj</code>. Though it won't call <code>obj</code>'s <code>__init__</code>, for that you will need some more voodoo/magic (if you're interested just post).</p> <pre><code>&gt;&gt;&gt; isinstance(second, A) True &gt;&gt;&gt; isinstance(second, B) False &gt;&gt;&gt; second.a 1 &gt;&gt;&gt; second.b Traceback (most recent call last): File "&lt;pyshell#15&gt;", line 1, in &lt;module&gt; second.b AttributeError: A instance has no attribute 'b' &gt;&gt;&gt; second.someFunc() Traceback (most recent call last): File "&lt;pyshell#16&gt;", line 1, in &lt;module&gt; second.someFunc() AttributeError: A instance has no attribute 'someFunc' &gt;&gt;&gt; second.b2 5 &gt;&gt;&gt; second.obj &lt;__main__.A instance at 0x0123CAF8&gt; </code></pre>
 

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