Python - Type Checking Instances of Objects
<p>I'm creating a class that emulates numeric types so as to be able to use basic arithmetic operators, like <code>+</code>, <code>-</code>, etc on instances of this class. However, I want to be able to handle the operation in different ways depending on what types the operands are. For instance, if I'm creating a class <code>foo_c</code> with <code>__add__()</code> as a function, then I want to be able to handle addition cases where one operand is of type <code>foo_c</code> and the other is of type <code>int</code> or <code>float</code> or <code>numpy.ndarray</code> (or <code>foo_c</code>).</p>

<p>The solution I want to implement is to have a collection of 'adder' functions to switch between based off of the operand type. The different functions are being assigned to a dictionary, as such:</p>

<pre><code>class foo_c:

   ...

   self.addOps = { int: self.addScalar,
                   float: self.addScalar,
                   foo_c: self.addFoo }

   ...

   self.addScalar(self, sclr):
      ...

   self.addFoo(self, foo):
      ...

   self.__add__(self, operand):
      return self.addOps[type(operand)](operand)
</code></pre>

<p>The problem that I'm having is that I can't get the <code>type()</code> function to return the appropriate value to be used as a key for the dictionary. After creating an instance of the class as <code>foo = foo_c()</code>, the built-in function <code>type(foo)</code> returns <code>instance</code>instead of <code>foo_c</code>. I assume this is because I'm not creating the object in question; rather I am creating an instance of the object. I've used <code>foo.__class__</code> as well, but am getting <code>__main__.foo_c</code> as the returned class, which isn't right either...</p>

<p>I don't want to have to use lines of <code>isinstance()</code> checks, so is there a way to get <code>type()</code> to return the class as desired?</p>

<p>You forgot to have <code>foo_c</code> inherit from <code>object</code>, so you're getting an old-style class. Make it inherit from <code>object</code>:</p>

<pre><code>class foo_c(object):
    ...
</code></pre>

python class object instance typechecking