0

I'm creating a class that emulates numeric types so as to be able to use basic arithmetic operators, like +, -, 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 foo_c with __add__() as a function, then I want to be able to handle addition cases where one operand is of type foo_c and the other is of type int or float or numpy.ndarray (or foo_c).

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:

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)

The problem that I'm having is that I can't get the type() function to return the appropriate value to be used as a key for the dictionary. After creating an instance of the class as foo = foo_c(), the built-in function type(foo) returns instanceinstead of foo_c. 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 foo.__class__ as well, but am getting __main__.foo_c as the returned class, which isn't right either...

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

1 Answer 1

1

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

class foo_c(object):
    ...
Sign up to request clarification or add additional context in comments.

3 Comments

So, I gave it a try, and the problem I'm getting now is that the type(foo) is still outputting __main__.foo_c as its type, which it's type should be foo_c without __main__.
@S.Gamgee: No, that's correct. __main__.foo_c is the right class - it's the foo_c class defined in the __main__ module.
Ok, I gotcha. I was operating in the IPython console and was executing type(foo) == foo_c() instead of type(foo) == foo_c. I'm good to go.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.