python six 用途_python之six用法
six.PY2 返回一个表示当前运行环境是否为python2的boolean值
six.PY3 返回一个表示当前运行环境是否为python3的boolean值
importsix,sysprint(six.PY2) #python2结果为True
print(six.PY3) #python3结果为True
sys.version_info[0]#PY2 = 2
sys.version_info[0] #PY3 = 3
sys.version_info[0:2] #PY34>= (3, 4)
常量
six.class_types
这里主要是针对python中的old-style和new-style, new-style为type, old-style为 types.ClassType。
python2中同时有old-style和new-style,python3中只有new-style。
six.integer_types
这里针对python2和python3中各自支持的int类型进行了区分:在python2中,存在 int 和 long 两种整数类型;在python3中,仅存在一种类型int。
six.string_types
这里针对python2和python3中各自的string类型进行了区分:在python2中,使用的为basestring;在python3中,使用的为str。
six.text_type
这里针对python2和python3中的文本字符进行了区分:在python2中,使用的文本字符的类型为unicode;在python3中使用的文本字符的类型为str。
six.MAXSIZE
list、string、dict以及其他的容器所能支持的最大尺寸。
ifPY3:
string_types=str,
integer_types=int,
class_types=type,
text_type=str
binary_type=bytes
MAXSIZE=sys.maxsizeelse:
string_types=basestring,
integer_types=(int, long)
class_types=(type, types.ClassType)
text_type=unicode
binary_type=strif sys.platform.startswith("java"):#Jython always uses 32 bits.
MAXSIZE = int((1 << 31) - 1)else:#It‘s possible to have sizeof(long) != sizeof(Py_ssize_t).
classX(object):def __len__(self):return 1 << 31
try:
len(X())exceptOverflowError:#32-bit
MAXSIZE = int((1 << 31) - 1)else:#64-bit
MAXSIZE = int((1 << 63) - 1)del X
对象模型兼容
six.get_unbound_function(meth)
针对python2和python3中unbound function的支持不同,在python2中存在unbound function,在python3中不存在unbound function。
ifPY3:defget_unbound_function(unbound):returnunboundelse:defget_unbound_function(unbound):return unbound.im_func
有关的测试代码如下:
>>> classFoo():
...defbar():
...print(1)
...deftoo(self):
...print(2)
...>>>
在python2的环境中:
>>>Foo.bar
>>>Foo().bar>
>>>Foo.too
>>>Foo().too>
在python3的环境中:
>>>Foo.bar
>>>Foo().bar>
>>>Foo.too
>>>Foo().bar>
使用six.get_unbound_function(meth):
在python2环境中:
>>> importsix>>>six.get_unbound_function(Foo.too)
>>>six.get_unbound_function(Foo.bar)
在python3环境中:
>>> importsix>>>six.get_unbound_function(Foo.too)
>>>six.get_unbound_function(Foo.bar)
six.get_method_function(meth)
此方法可以在方法对象之外得到函数。在python2中使用im_func, 在python3中使用__func__。
ifPY3:
_meth_func= "__func__"
else:
_meth_func= "im_func"get_method_function= operator.attrgetter(_meth_func)
有关的测试代码如下:
>>> classFoo():
...defbar():
...print(1)
...deftoo(self):
...print(2)
...>>>
在python2环境中:
>>> importsix>>>six.get_method_function(Foo().bar)
>>>six.get_method_function(Foo.bar)
>>>six.get_method_function(Foo().too)
>>>six.get_method_function(Foo.too)
在python3环境中:
>>> importsix>>>six.get_method_function(Foo.bar)
Traceback (most recent call last):
File"", line 1, in AttributeError:‘function‘ object has no attribute ‘__func__‘
>>>six.get_method_function(Foo().bar)
>>>six.get_method_function(Foo.too)
Traceback (most recent call last):
File"", line 1, in AttributeError:‘function‘ object has no attribute ‘__func__‘
>>>six.get_method_function(Foo().too)
six.get_method_self(meth)
针对python2以及python3中的不同,返回bound method的self。其中:python2中使用im_self,python3中使用__self__。
ifPY3:
_meth_self= "__self__"
else:
_meth_self= "im_self"get_method_self= operator.attrgetter(_meth_self)
有关的测试代码如下:
>>> classFoo():
...defbar():
...print(1)
...deftoo(self):
...print(2)
...>>>
在python2的环境中:
>>> importsix>>>six.get_method_self(Foo.bar)>>> a =six.get_method_self(Foo.bar)>>>a>>>six.get_method_self(Foo().bar)<__main__.foo instance at>
>>> a =six.get_method_self(Foo().bar)>>>a<__main__.foo instance at>
>>>six.get_method_self(Foo.too)>>> a =six.get_method_self(Foo.too)>>>a>>>six.get_method_self(Foo().too)<__main__.foo instance at>
>>> a =six.get_method_self(Foo().too)>>>a<__main__.foo instance at>
在python3的环境中:
>>> importsix>>>six.get_method_self(Foo.bar)
Traceback (most recent call last):
File"", line 1, in AttributeError:‘function‘ object has no attribute ‘__self__‘
>>>six.get_method_self(Foo().bar)<__main__.foo object at>
>>>six.get_method_self(Foo.too)
Traceback (most recent call last):
File"", line 1, in AttributeError:‘function‘ object has no attribute ‘__self__‘
>>>six.get_method_self(Foo().too)<__main__.foo object at>
six.get_function_closure(func)
针对python2和python3中的不同,返回函数当中的闭包。其中,python2使用func_closure,python3使用 __closure__。
ifPY3:
_func_closure= "__closure__"
else:
_func_closure= "func_closure"get_function_closure= operator.attrgetter(_func_closure)
关于闭包的理解可以参考:
有关的测试代码如下:
>>> deffoo(n):
... a= 1...defbar(n):
...return a-n
...return bar
此处需要注意的是foo函数返回的是bar函数,而不是具体的值。
在python2的环境当中:
>>> foo.__closure__
>>> foo(1)
>>> foo(1).__closure__(,)>>> foo(1).func_closure
(,)
在python3的环境当中:
>>> foo.__closure__
>>> foo(1).bar at 0x10c46dbf8>
>>> foo(1).__closure__(,)>>> foo(1).func_closure
Traceback (most recent call last):
File"", line 1, in AttributeError:‘function‘ object has no attribute ‘func_closure‘
six.get_function_code(func)
针对python2和python3中获取func中的code对象,将使用不同的方式进行获取。在python2中,将使用func_code;在python3中,将使用code。
ifPY3:
_func_code= "__code__"
else:
_func_code= "func_code"get_function_code= operator.attrgetter(_func_code)
如果你对其中的code object是什么比较感兴趣,可以参考下面的资料:
有关的测试代码如下:
>>> defboo():
...return 1
在python2的环境当中:
>>>boo.func_code", line 1>
>>>boo().func_code
Traceback (most recent call last):
File"", line 1, in AttributeError:‘int‘ object has no attribute ‘func_code‘
在python3的环境当中:
>>> boo.__code__
", line 1>
>>> boo().__code__Traceback (most recent call last):
File"", line 1, in AttributeError:‘int‘ object has no attribute ‘__code__‘
six.get_function_defaults(func)
针对python2和python3中的区别,获取func中的默认元组。在python2中,使用func_defaults;在python3中,使用__defaults__。
ifPY3:
_func_defaults= "__defaults__"
else:
_func_defaults= "func_defaults"get_function_defaults= operator.attrgetter(_func_defaults)
有关的测试代码如下:
>>> def boo(a=1):
...returna
...
在python2环境中:
>>>boo.func_defaults
(1,)>>> boo.__defaults__(1,)>>>boo().func_defaults
Traceback (most recent call last):
File"", line 1, in AttributeError:‘int‘ object has no attribute ‘func_defaults‘
>>> boo().__defaults__Traceback (most recent call last):
File"", line 1, in AttributeError:‘int‘ object has no attribute ‘__defaults__‘
在python3环境中:
>>> boo.__defaults__(1,)>>>boo.func_defaults
Traceback (most recent call last):
File"", line 1, in AttributeError:‘function‘ object has no attribute ‘func_defaults‘
>>> boo().__defaults__Traceback (most recent call last):
File"", line 1, in AttributeError:‘int‘ object has no attribute ‘__defaults__‘
>>>boo().func_defaults
Traceback (most recent call last):
File"", line 1, in AttributeError:‘int‘ object has no attribute ‘func_defaults‘
six.get_function_globals(func)
获取函数当中的全局变量。在python2中,使用func_globals;在python3中,使用__globals__。
ifPY3:
_func_globals= "__globals__"
else:
_func_globals= "func_globals"get_function_globals= operator.attrgetter(_func_globals)
有关的测试代码:
>>> def boo(a=1):
... x= 100... b= x -a
...return b
在python2环境中:
>>> boo.__globals__{‘__builtins__‘: , ‘__name__‘: ‘__main__‘, ‘boo‘: , ‘__doc__‘: None, ‘__package__‘: None}>>>boo.func_globals
{‘__builtins__‘: , ‘__name__‘: ‘__main__‘, ‘boo‘: , ‘__doc__‘: None, ‘__package__‘: None}
在python3环境中:
>>> boo.__globals__{‘__name__‘: ‘__main__‘, ‘__doc__‘: None, ‘__package__‘: None, ‘__loader__‘: , ‘__spec__‘: None, ‘__annotations__‘: {}, ‘__builtins__‘: , ‘boo‘: }>>>boo.func_globals
Traceback (most recent call last):
File"", line 1, in AttributeError:‘function‘ object has no attribute ‘func_globals‘
six.next(it) or six.advance_iterator(it)
获取到迭代器的下一个。在python2环境中,使用it.next();在python3环境中,使用next(it)
try:
advance_iterator=nextexceptNameError:defadvance_iterator(it):returnit.next()
next= advance_iterator
关于迭代器的内容可以参考一下文件:
在python2环境中:
>>> it = iter([1,2,3,4,5])>>> whileTrue:
...try:
... x=it.next()
...exceptNameError:
...print "name error"...exceptStopIteration:
...print "end"...break...
end>>> it = iter([1,2,3,4,5])>>> whileTrue:
...try:
... x=next(it)
...exceptNameError:
...print "name error"...exceptStopIteration:
...print "end"...break...
end
在python3环境中:
>>> it = iter([1,2,3,4,5])>>> whileTrue:
...try:
... x=it.next()
...exceptNameError:
...print("name error")
...exceptStopIteration:
...print("end")
...break...
Traceback (most recent call last):
File"", line 3, in AttributeError:‘list_iterator‘ object has no attribute ‘next‘
>>> it = iter([1,2,3,4,5])>>> whileTrue:
...try:
... x=next(it)
...exceptNameError:
...print("name error")
...exceptStopIteration:
...print("end")
...break...
end
six.callable(obj)
该方法用来检验obj是否可以进行调用。
关于python的callable属性,请参考一下文件:
try:
callable=callableexceptNameError:defcallable(obj):return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)
有关的测试代码:
>>> defadd(x, y):
...return x +y
...
在python2环境中:
>>>callable(add)
True
在python 3.1环境中:
>>>callable(add)
Traceback (most recent call last):
File"", line 1, in NameError: name‘callable‘ is not defined
在python3.2之后的环境中:
>>>callable(add)
True
python six 用途_python之six用法相关推荐
- python星号正方形_Python星号*与**用法分析
本文实例分析了Python星号*与**用法.分享给大家供大家参考,具体如下: 1. 加了星号(*)的变量名会存放所有未命名的变量参数,不能存放dict,否则报错. 如: def multiple(ar ...
- python管道界面_python中管道用法入门实例
本文实例讲述了python中管道用法.分享给大家供大家参考.具体如下: #!coding=utf-8 import multiprocessing def consumer(pipe): output ...
- python pillow库_python pillow模块用法
pillow Pillow是PIL的一个派生分支,但如今已经发展成为比PIL本身更具活力的图像处理库.pillow可以说已经取代了PIL,将其封装成python的库(pip即可安装),且支持pytho ...
- python守护线程_Python守护线程用法实例
本文实例讲述了Python守护线程用法.分享给大家供大家参考,具体如下: 如果你设置一个线程为守护线程,就表示你在说这个线程是不重要的,在进程退出的时候,不用等待这个线程退出.如果你的主线程在退出的时 ...
- python局部变量函数_python函数局部变量用法实例分析
本文实例讲述了python函数局部变量用法.分享给大家供大家参考.具体分析如下: 当你在函数定义内声明变量的时候,它们与函数外具有相同名称的其他变量没有任何关系,即变量名称对于函数来说是 局部 的.这 ...
- python crypt模块_Python常见加密模块用法分析【MD5,sha,crypt模块】
本文实例讲述了Python常见加密模块用法.分享给大家供大家参考,具体如下: 1. md5模块 md5.new([arg]) 返回一个md5对象,如果给出参数,则相当于调用了update(arg) m ...
- python分词设计_Python smallseg分词用法实例分析
这篇文章主要介绍了Python smallseg分词用法,以实例形式分析了Python实现分析的相关技巧,需要的朋友可以参考下 本文实例讲述了Python smallseg分词用法.分享给大家供大家参 ...
- python函数形参_python函数形参用法实例分析
本文实例讲述了python函数形参用法.分享给大家供大家参考.具体如下: 函数形参: 函数取得的参数是你提供给函数的值,这样函数就可以利用这些值 做 一些事情.这些参数就像变量一样,只不过它们的值是在 ...
- tuple python怎么用_python tuple基本用法
标签: 最近学习Django,在配置templates的路径TEMPLATE_DIRS的时候,死活要给我抱一个错:The TEMPLATE_DIRS setting must a tuple.原来tu ...
最新文章
- 018_switch语句
- 机器学习算法基础——朴素贝叶斯算法
- Github【网站打不开 / 创建仓库 / 创建文件】
- 独家|一文带你理解机器学习中的“归纳偏好”真正含义!
- 杀不死的人狼——我读《人月神话》(四)
- #ifdef __cplusplus extern C { #endif”的定义
- golang map转json的顺序问题
- 【高效复习】《数据库系统概论》王珊版
- 一个自动写咪蒙体的机器人,请夸我
- Power query (Power BI)一步到位傻瓜式合并工作簿,史上最好用
- m1芯片的mac怎样安装PS2021 m1芯片的mac安装Photoshop21适配版解决方案 2021最新方法
- python三维曲面拟合_用Python拟合多项式曲面
- IDEA 编译gong'chenError:(1, 1) 错误: 非法字符: '\ufeff'
- 任正非:小公司别讲复杂价值观 认真磨好豆腐就有人买
- 中小项目敏捷实践之一(关于项目所有者和责任人)
- split( )[3].split(:)[0];
- 别告诉我你会记笔记——工作中如何使用笔记(笔记)
- The JAVA_HOME environment variable is not defined correctly,
- 最新互普威盾4.62 威盾4.5 4.33 互普威盾3.59 溢信IPGuard4.62 ip-guard4.5 IPguard4.33 IPGuard3.59 ip-guard4.51注册授权
- 简易android手电筒app
热门文章
- android导入音频格式,如何把音乐导入android手机?
- java查询图片前台展示_Java +spring MVC 后台图片流在前台页面显示
- 在Java中实现 点击返回按钮返回上一个页面
- 苹果可穿戴设备项目背后的那些专家
- 杨云华师大计算机,2017-2018学年第二学期教师辅导-华东师范大学计算中心网站.DOC...
- Python采集--小说一键保存txt文本
- JavaScript新人总结
- UDS 服务 Service 0x31 - RoutineControl
- 四 微信公众号 基础参数说明
- [C语言]指针之数组逆序函数:编写函数invert,将数组中的n个整数按相反顺序存放,要求用指针变量作为函数形参,并用指针的方法遍历该数组。在main函数中输入n个整数,存入数组a中;然后调用上述函