如何在python中制作通用类型检查器

时间:2016-02-17 11:27:36

标签: python types introspection isinstance

我有一些类似的代码。不是很冒险,但我不是很多,但我需要 check_type 接受 r_type 参数作为字符串并检查对象类型是否具有此字符串的值。这是可行的吗?!?!?

我重申不能这样做: n.check_type(r_type = Newer)* ,我需要从配置文件中取 r_type 值,那样就是串!

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

输出:

        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

2 个答案:

答案 0 :(得分:3)

您可以使用global字典按名称获取实际类,并使用它来检查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
>>> 

答案 1 :(得分:0)

您可以直接比较类型的名称,而不是尝试调用isInstance

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

显然,您可能希望使用类型名称来提取该类型的基本名称并进行比较,以便于指定:)

相关问题