0

I have a use case where I want to get another class based upon the type of object.

For one solution, I have created a dict where I am maintaining this relation and using type to match among classes.

For example, consider the below code

class classA(object):
    def __init__(self):
        print "A called"

class classB(object):
    def __init__(self):
        print "B called"

MAP = {
   A: classA,
   B: classB
}

class C(object):
    pass

class A(C):
    pass

class B(C):
    pass

obj can be object of A or B.

new_cls = MAP.get(type(obj), 'None')
new_obj = new_cls()

Is there a better way to achieve this?

Deepanshu Arora
  • 375
  • 1
  • 5
  • 21

2 Answers2

2

why not to:

class C(object):
    pass

class A(C):
    def call:
        print("A")

class B(C):
    def call:
        print("B")
obj.call()

or use the inheritance.

But wait , what if i can't do this and really need to know which class is this??

you can use this obj.__class__.__name__ this will work for old style and new style Classes

1

Looks like you're trying to reinvent type-based polymorphic dispatch...

I assume you don't have the hand on classes A and B (=> they belong to the stdlib or a third-part one that you don't want to fork), else the very obvious solution would be to simply implement call (or any other method) on those classes directly.

In this context, your solution is actually quite pythonic. The other possible pythonic solution would be using functools.singledispatch, and the last resort evil ugly but-sometimes-a-lifesaver solution to monkeypatch A and B.

bruno desthuilliers
  • 75,974
  • 6
  • 88
  • 118
  • can you check my edited question, does this holds true also if instead of methods, i require different class types to create an object – Deepanshu Arora Aug 12 '19 at 13:19
  • @DeepanshuArora python has a notion of "callable object" (https://docs.python.org/3/library/functions.html#callable). Functions are callable, methods are callable, classes are callable (that's how you instanciate them), and you can define your own callables. My answer applies to all callable objects. – bruno desthuilliers Aug 12 '19 at 13:27