Python(10):判断变量的类型

python由于变量可以不经定义就直接使用,作为初学者经常会有搞不清楚变量类型的情况,因此找到了一个非常方便的用于判断python基础变量类型的方法

如下

def typeof(variate):
    type = None
    if isinstance(variate, int):
        type = "int"
    elif isinstance(variate, str):
        type = "str"
    elif isinstance(variate, float):
        type = "float"
    elif isinstance(variate, list):
        type = "list"
    elif isinstance(variate, tuple):
        type = "tuple"
    elif isinstance(variate, dict):
        type = "dict"
    elif isinstance(variate, set):
        type = "set"
    return type

使用起来也很方便

def typeof(variate):
    type = None
    if isinstance(variate, int):
        type = "int"
    elif isinstance(variate, str):
        type = "str"
    elif isinstance(variate, float):
        type = "float"
    elif isinstance(variate, list):
        type = "list"
    elif isinstance(variate, tuple):
        type = "tuple"
    elif isinstance(variate, dict):
        type = "dict"
    elif isinstance(variate, set):
        type = "set"
    return type

if __name__ == '__main__':
    var = 'abc'
    var2 = 3
    print(typeof(var))
    print(typeof(var2))

输出

str
int

 

《Python(10):判断变量的类型》

    原文作者:Just_like_fire
    原文地址: https://blog.csdn.net/Leo_csdn_/article/details/89349670
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞