• python的types模块


    python的types模块

    1.types是什么:

    • types模块中包含python中各种常见的数据类型,如IntType(整型),FloatType(浮点型)等等。
    >>> 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',
     '__all__',
     '__builtins__',
     '__doc__',
     '__file__',
     '__name__',
     '__package__']
    

    2.types常见用法:

    # 100是整型吗?
    >>> isinstance(100, types.IntType)
    True
     
    >>>type(100)
    int
     
    # 看下types的源码就会发现types.IntType就是int
    >>> types.IntType is int
    True
    
    • 但有些类型并不是int这样简单的数据类型:
     
    class Foo:
        def run(self):
            return None
     
    def bark(self):
        print('barking')
     
    a = Foo()
     
    print(type(1))
    print(type(Foo))
    print(type(Foo.run))
    print(type(Foo().run))
    print(type(bark))
    

    输出结果:

    <class 'int'>
    <class 'type'>
    <class 'function'>
    <class 'method'>
    <class 'function'>
    
    • python中总有些奇奇怪怪的类型。有些类型默认python中没有像int那样直接就有,单但其实也可以自己定义的。
    >>> import types
     
    >>> class Foo:
            def run(self):
                return None
        
        def bark(self):
            print('barking')
     
    # Foo.run是函数吗?
    >>> isinstance(Foo.run, types.FunctionType)
    True
     
    # Foo().run是方法吗?
    >>> isinstance(Foo().run, types.MethodType)
    True
     
    # 其实:
    >>> types.FunctionType is type(Foo.run)
    True
     
    >>> types.MethodType is type(Foo().run)
    True
    

    3.MethodType动态的给对象添加实例方法:

    import types
    class Foo:
        def run(self):
            return None
     
    def bark(self):
        print('i am barking')
     
    a = Foo()
    a.bark = types.MethodType(bark, a)
    a.bark()
    

    如果不用MethodType而是直接a.bark = bark的话,需要在调用bark时额外传递self参数,这不是我们想要的。

    ————————————————
    版权声明:本文为CSDN博主「XYES@fff」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/qq_42604178/article/details/103135121

  • 相关阅读:
    PS3 可播放的多媒体类型
    VB个性化文件夹图标
    Delphi源码:编辑长求字符串相似度
    Delphi使用zlib来压缩文件
    汉字编码问题
    Silverlight 3 学习概要
    asp.net下大文件上传知识整理
    DHTML动态创建一个弹出遮罩层
    Delphi的运算符重载
    Windows Vista 交互式服务编程
  • 原文地址:https://www.cnblogs.com/hanfe1/p/16719908.html
Copyright © 2020-2023  润新知