types 模块

来源:互联网 发布:网络音频编码器 编辑:程序博客网 时间:2024/04/30 07:21

python的types 模块:


1.怎么判断一个对象的类型?
Python内建函数type(object),用于返回当前object对象的类型。types模块定义了python中所有的类型,包括NoneType, TypeType, ObjectType....


import types


def check(object):
    print object,


    if type(object) is types.IntType:
        print "INTEGER",
    if type(object) is types.FloatType:
        print "FLOAT",
    if type(object) is types.StringType:
        print "STRING",
    if type(object) is types.ClassType:
        print "CLASS",
    if type(object) is types.InstanceType:
        print "INSTANCE",
    print


check(0)  -->"INTEGER"
check(0.0)  -->"FLOAT"
check("0")  -->"STRING"




2.types支持的type种类有多少?
import types
dir(types)


['BooleanType', 'BufferType', 'BuiltinFunctionType', 'BuiltinMethodType', 'ClassType', 'CodeType', 'ComplexType', 'DictProxyType', 'DictType', 'DictionaryType', 'EllipsisType', 'FileType', 'FloatType', 'FrameType', 'FunctionType', 'GeneratorType', 'GetSetDescriptorType', 'InstanceType', 'IntType', 'LambdaType', 'ListType', 'LongType', 'MemberDescriptorType', 'MethodType', 'ModuleType', 'NoneType', 'NotImplementedType', 'ObjectType', 'SliceType', 'StringType', 'StringTypes', 'TracebackType', 'TupleType', 'TypeType', 'UnboundMethodType', 'UnicodeType', 'XRangeType', '__builtins__', '__doc__', '__file__', '__name__', '__package__']




3.types的缺点
如果是判断自定义类(该类继承基础类比如int),那个该自定义类的示例对象可能不是types.IntType. 所以 推荐isinstance(object, classifo)函数来替代。
0 0
原创粉丝点击