简体   繁体   中英

Python “isinstance” with class name instead of type

I want to check if an object or variable is an instance of the specified class type, but using the name of this class, not its type. Something like this:

class A: pass

class B(A): pass

class C(B): pass

c_inst = C()

# Not working, isinstance expects the type:
ok = isinstance(c_inst, 'A')

Are there any alternatives? I wnat to use the class name, so isinstance(c_inst, A) is not available in this case.

If you only have the class name as a string, you could do this

>>> class Foo:pass
... 
>>> foo = Foo()
>>> foo.__class__.__name__ == 'Foo'
True
>>> foo.__class__.__name__ == 'Bar'
False

However this isn't very reliable, because Foo.__class__.__name__ is writeable

>>> foo.__class__.__name__ = 'Baz'
>>> foo.__class__.__name__ == 'Foo'
False

For superclasses, you could do something like

foo.__class__.__name__ = 'X' or 'X' in {c.__name__ for c in foo.__class__.__bases__}

though this won't pick up object .

Came up with this way, note: the class you are checking must be in globals though:

import inspect

def isinstance_string(variable, string):
    cls = globals().get(string, None)
    class Unused:
        pass
    cls = cls or Unused
    if inspect.isclass(cls):
        return isinstance(variable, cls)
    return False

class A: pass

class B(A): pass

class C(B): pass

c_inst = C()
ok = isinstance_string(c_inst, 'A')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM