python中的types是什么模块_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))

输出结果:

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值