简体   繁体   English

Python “isinstance” 使用 class 名称而不是类型

[英]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.我想检查 object 或变量是否是指定 class 类型的实例,但使用此 class 的名称,而不是其类型。 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.我想使用 class 名称,因此在这种情况下isinstance(c_inst, A)不可用。

If you only have the class name as a string, you could do this如果您只有 class 名称作为字符串,您可以这样做

>>> 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__是可写的

>>> 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 .虽然这不会拿起object

Came up with this way, note: the class you are checking must be in globals though:想出了这种方式,请注意:您正在检查的 class 必须在全局变量中:

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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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