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
  • 瞬间感觉types模块号low,直接用type都能代替。。事实就是这样

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参数,这不是我们想要的。


原文链接:https://www.cnblogs.com/PrettyTom/p/6664808.html