How to check if a variable's type is primitive?

前端 未结 7 1202
难免孤独
难免孤独 2020-12-05 12:57

I don\'t know how to check if a variable is primitive. In Java it\'s like this:

if var.isPrimitive():
7条回答
  •  忘掉有多难
    2020-12-05 13:49

    As every one says, there is no primitive types in python. But I believe, this is what you want.

    def isPrimitive(obj):
        return not hasattr(obj, '__dict__')
    
    isPrimitive(1) => True
    isPrimitive("sample") => True
    isPrimitive(213.1311) => True
    isPrimitive({}) => True
    isPrimitive([]) => True
    isPrimitive(()) => True
    
    
    class P:
        pass
    
    isPrimitive(P) => False
    isPrimitive(P()) => False
    
    def func():
        pass
    
    isPrimitive(func) => False
    

提交回复
热议问题