开发者

Is there something like python's issubclass which will return False if the first arg is not a Class?

I'd like issubclass(1开发者_StackOverflow社区, str) to return false, 1 is not a subclass of str. Because it's not a class at all I get a TypeError.

Is there a good way to test this without resorting to a try, except?

try:
    if issubclass(value, MyClass):
        do_stuff()
except TypeError:
    pass


You seem to want isinstance:

>>> isinstance(1, str)
False


import inspect
def isclassandsubclass(value, classinfo):
    return inspect.isclass(value) and issubclass(value, classinfo)


Without importing any module:

def issubclass_(c, clazz):
    return isinstance(c, type) and issubclass(c, clazz)


Not sure what your usecase is but checking against a class or an instance of a class are too completely different things (and have different API methods: issubclass() vs. isinstance()).

So you always have to check if your 'item' is an instance of something of a class.

>

>> (1).__class__
<type 'int'>
>>> (1).__class__.__class__
<type 'type'>


you could simply check before calling issubclass():

import types

def myissubclass (c, sc):
    if type(c) != types.ClassType
        return False
    return issubclass (c, sc)

but I think it would be more pythonic to embrace exceptions:

def myissubclass (c, sc):
    try:
        return issubclass (c, sc)
    except TypeError:
        return False
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜