0

I got some similar code to this. Not exacly, but I don't to put to much, but I need that check_type accept r_type parameter as string and check if object type is of value of this string. It is doable?!?!?

I repeat can't do that: n.check_type(r_type=Newer)*, I need take r_type value from configuration file and thats way is a string!

    class New(object):
        def check_type(self, r_type):
            print 'is instance of r_type: ', isinstance(self, r_type)
            return isinstance(self, r_type)

    class Newer(New):
        pass

    if __name__ == '__main__':
        n = Newer()
        n.check_type(r_type='Newer')

Output:

        print 'is instance of r_type: ', isinstance(self, r_type)
    TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types
emcek
  • 459
  • 1
  • 6
  • 17
  • It's customary to accept answers that help you, by clicking the tick next to them. I see you haven't discovered this yet - if you want to continue getting good help here, you need to find it :) – GreenAsJade Feb 17 '16 at 23:28

2 Answers2

3

you can use the global dictionary to get the actual class by its name and use it to check with isinstance

>>> class New(object):
        def check_type(self,r_type):
            result = isinstance(self,globals()[r_type])
            print "is instance of r_type: ",result
            return result


>>> class Newer(New):
        pass

>>> n=Newer()
>>> n.check_type("Newer")
is instance of r_type:  True
True
>>> 
Copperfield
  • 8,131
  • 3
  • 23
  • 29
0

Instead of trying to call isInstance, you could just compare the names of the types directly:

class New(object):
    def check_type(self, r_type):
        return str(type(self)) == r_type

class Newer(New):
    pass

if __name__ == '__main__':
    n = Newer()
    print n.check_type(r_type="<class '__main__.Newer'>")

Obviously, you might want to munge the type name to extract just the basename of the type and compare that, for ease of specifying :)

GreenAsJade
  • 14,459
  • 11
  • 63
  • 98