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

posted @   hanfe1  阅读(1573)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示