Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There is no "casting" in Python. Any subclass of a class is considered an instance of its parents. Desired behavior can be achieved by proper calling the superclass methods, and by overriding class attributes.</p> <p>What you can do on your example, is to have to have a subclass initializer that receives the superclass and copies its relevant attributes - so, your MutantReturnstatement could be written thus:</p> <pre><code>class MutantReturnStatement(ReturnStatement): def __init__(self, previous_object=None): if previous_object: self.attribute = previous_object.attribute # repeat for relevant attributes def act(self): print "I'm wrapping ReturnStatement." return ReturnStatement().act() </code></pre> <p>And then change your MutantWorking class to:</p> <pre><code>class MutantWorking(Working): def do(self): print "I am wrapping Working." return MutantReturnStatement(Working().do()) </code></pre> <p>There are Pythonic ways for not having a lot of <code>self.attr = other.attr</code> lines on the <code>__init__</code>method if there are lots (like, more than 3 :-) ) attributes you want to copy - the laziest of which wiuld be simply to copy the other instance's <code>__dict__</code> attribute. </p> <p>Alternatively, <strong>if you know what you are doing</strong>, you could also simply change the <code>__class__</code> attribute of your target object to the desired class - but that can be misleading and carry you to subtle errors (the <code>__init__</code> method of the subclass would not be called, would not work on non-python defined classes, and other possible problems), I don't recomment this approach - this is not "casting", it is use of introspection to bruteforce an object change and is only included for keeping the answer complete:</p> <pre><code>class MutantWorking(Working): def do(self): print "I am wrapping Working." result = Working.do(self) result.__class__ = MutantReturnStatement return result </code></pre> <p>Again - this should work, but don't do it - use the former method.</p> <p>By the way, I am not too experienced with other OO languages, that allow casting - but is casting to a subclass even allowed in any language? Does it make sense? I think casting s only allowed to parentclasses.</p>
    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.
 

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