热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

[245]python之six用法

six.PY2返回一个表示当前运行环境是否为python2的boolean值six.PY3返回一个表示当前运行环境是否为python3的boolean值importsix,sy

six.PY2 返回一个表示当前运行环境是否为python2的boolean值

six.PY3 返回一个表示当前运行环境是否为python3的boolean值

import six,sysprint(six.PY2) #python2结果为True
print(six.PY3) #python3结果为Truesys.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。

具体可以参考Python2 与 Python3 的编码对比

  • six.MAXSIZE

list、string、dict以及其他的容器所能支持的最大尺寸。

if PY3:string_types = str,integer_types = int,class_types = type,text_type = strbinary_type = bytesMAXSIZE = sys.maxsize
else:string_types &#61; basestring,integer_types &#61; (int, long)class_types &#61; (type, types.ClassType)text_type &#61; unicodebinary_type &#61; strif sys.platform.startswith("java"):# Jython always uses 32 bits.MAXSIZE &#61; int((1 <<31) - 1)else:# It&#39;s possible to have sizeof(long) !&#61; sizeof(Py_ssize_t).class X(object):def __len__(self):return 1 <<31try:len(X())except OverflowError:# 32-bitMAXSIZE &#61; int((1 <<31) - 1)else:# 64-bitMAXSIZE &#61; int((1 <<63) - 1)del X

对象模型兼容


  • six.get_unbound_function(meth)

针对python2和python3中unbound function的支持不同&#xff0c;在python2中存在unbound function&#xff0c;在python3中不存在unbound function。

if PY3:def get_unbound_function(unbound):return unbound
else:def get_unbound_function(unbound):return unbound.im_func

有关的测试代码如下:

>>> class Foo():
... def bar():
... print(1)
... def too(self):
... print(2)
...
>>>

在python2的环境中&#xff1a;

>>> Foo.bar

>>> Foo().bar
>
>>> Foo.too

>>> Foo().too
>

在python3的环境中&#xff1a;

>>> Foo.bar

>>> Foo().bar
>
>>> Foo.too

>>> Foo().bar
>

使用six.get_unbound_function(meth)&#xff1a;

在python2环境中&#xff1a;

>>> import six
>>> six.get_unbound_function(Foo.too)

>>> six.get_unbound_function(Foo.bar)

在python3环境中&#xff1a;

>>> import six
>>> six.get_unbound_function(Foo.too)

>>> six.get_unbound_function(Foo.bar)


  • six.get_method_function(meth)

此方法可以在方法对象之外得到函数。在python2中使用im_func, 在python3中使用__func__

if PY3:_meth_func &#61; "__func__"
else:_meth_func &#61; "im_func"
get_method_function &#61; operator.attrgetter(_meth_func)

有关的测试代码如下:

>>> class Foo():
... def bar():
... print(1)
... def too(self):
... print(2)
...
>>>

在python2环境中&#xff1a;

>>> import six
>>> 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环境中&#xff1a;

>>> import six
>>> six.get_method_function(Foo.bar)
Traceback (most recent call last):File "", line 1, in
AttributeError: &#39;function&#39; object has no attribute &#39;__func__&#39;
>>> six.get_method_function(Foo().bar)

>>> six.get_method_function(Foo.too)
Traceback (most recent call last):File "", line 1, in
AttributeError: &#39;function&#39; object has no attribute &#39;__func__&#39;
>>> six.get_method_function(Foo().too)


  • six.get_method_self(meth)

针对python2以及python3中的不同&#xff0c;返回bound method的self。其中&#xff1a;python2中使用im_self&#xff0c;python3中使用__self__。

if PY3:_meth_self &#61; "__self__"
else:_meth_self &#61; "im_self"
get_method_self &#61; operator.attrgetter(_meth_self)

有关的测试代码如下:

>>> class Foo():
... def bar():
... print(1)
... def too(self):
... print(2)
...
>>>

在python2的环境中&#xff1a;

>>> import six
>>> six.get_method_self(Foo.bar)
>>> a &#61; six.get_method_self(Foo.bar)
>>> a
>>> six.get_method_self(Foo().bar)
<__main__.Foo instance at 0x10563da70>
>>> a &#61; six.get_method_self(Foo().bar)
>>> a
<__main__.Foo instance at 0x10563dd88>
>>> six.get_method_self(Foo.too)
>>> a &#61; six.get_method_self(Foo.too)
>>> a
>>> six.get_method_self(Foo().too)
<__main__.Foo instance at 0x10563da28>
>>> a &#61; six.get_method_self(Foo().too)
>>> a
<__main__.Foo instance at 0x10563da70>

在python3的环境中&#xff1a;

>>> import six
>>> six.get_method_self(Foo.bar)
Traceback (most recent call last):File "", line 1, in
AttributeError: &#39;function&#39; object has no attribute &#39;__self__&#39;
>>> six.get_method_self(Foo().bar)
<__main__.Foo object at 0x1059bbb00>
>>> six.get_method_self(Foo.too)
Traceback (most recent call last):File "", line 1, in
AttributeError: &#39;function&#39; object has no attribute &#39;__self__&#39;
>>> six.get_method_self(Foo().too)
<__main__.Foo object at 0x1059bbb38>

  • six.get_function_closure(func)

针对python2和python3中的不同&#xff0c;返回函数当中的闭包。其中&#xff0c;python2使用func_closure&#xff0c;python3使用 closure

if PY3:_func_closure &#61; "__closure__"
else:_func_closure &#61; "func_closure"get_function_closure &#61; operator.attrgetter(_func_closure)

关于闭包的理解可以参考:

  1. 浅显理解 Python 闭包
  2. 闭包的概念、形式与应用

有关的测试代码如下&#xff1a;

>>> def foo(n):
... a &#61; 1
... def bar(n):
... return a-n
... return bar

此处需要注意的是foo函数返回的是bar函数&#xff0c;而不是具体的值。

在python2的环境当中&#xff1a;

>>> foo.__closure__
>>> foo(1)

>>> foo(1).__closure__
(,)
>>> foo(1).func_closure
(,)

在python3的环境当中&#xff1a;

>>> foo.__closure__
>>> foo(1)
.bar at 0x10c46dbf8>
>>> foo(1).__closure__
(,)
>>> foo(1).func_closure
Traceback (most recent call last):File "", line 1, in
AttributeError: &#39;function&#39; object has no attribute &#39;func_closure&#39;

  • six.get_function_code(func)

针对python2和python3中获取func中的code对象&#xff0c;将使用不同的方式进行获取。在python2中&#xff0c;将使用func_code&#xff1b;在python3中&#xff0c;将使用__code__。

if PY3:_func_code &#61; "__code__"
else:_func_code &#61; "func_code"
get_function_code &#61; operator.attrgetter(_func_code)

如果你对其中的code object是什么比较感兴趣&#xff0c;可以参考下面的资料&#xff1a;

  1. Exploring Python Code Objects

有关的测试代码如下&#xff1a;

>>> def boo():
... return 1

在python2的环境当中&#xff1a;

>>> boo.func_code
", line 1>
>>> boo().func_code
Traceback (most recent call last):File "", line 1, in
AttributeError: &#39;int&#39; object has no attribute &#39;func_code&#39;

在python3的环境当中&#xff1a;

>>> boo.__code__
", line 1>
>>> boo().__code__
Traceback (most recent call last):File "", line 1, in
AttributeError: &#39;int&#39; object has no attribute &#39;__code__&#39;

  • six.get_function_defaults(func)

针对python2和python3中的区别&#xff0c;获取func中的默认元组。在python2中&#xff0c;使用func_defaults&#xff1b;在python3中&#xff0c;使用__defaults__

if PY3:_func_defaults &#61; "__defaults__"
else:_func_defaults &#61; "func_defaults"
get_function_defaults &#61; operator.attrgetter(_func_defaults)

有关的测试代码如下:

>>> def boo(a&#61;1):
... return a
...

在python2环境中&#xff1a;

>>> boo.func_defaults
(1,)
>>> boo.__defaults__
(1,)
>>> boo().func_defaults
Traceback (most recent call last):File "", line 1, in
AttributeError: &#39;int&#39; object has no attribute &#39;func_defaults&#39;
>>> boo().__defaults__
Traceback (most recent call last):File "", line 1, in
AttributeError: &#39;int&#39; object has no attribute &#39;__defaults__&#39;

在python3环境中:

>>> boo.__defaults__
(1,)
>>> boo.func_defaults
Traceback (most recent call last):File "", line 1, in
AttributeError: &#39;function&#39; object has no attribute &#39;func_defaults&#39;
>>> boo().__defaults__
Traceback (most recent call last):File "", line 1, in
AttributeError: &#39;int&#39; object has no attribute &#39;__defaults__&#39;
>>> boo().func_defaults
Traceback (most recent call last):File "", line 1, in
AttributeError: &#39;int&#39; object has no attribute &#39;func_defaults&#39;

  • six.get_function_globals(func)

获取函数当中的全局变量。在python2中&#xff0c;使用func_globals&#xff1b;在python3中&#xff0c;使用__globals__

if PY3:_func_globals &#61; "__globals__"
else:_func_globals &#61; "func_globals"
get_function_globals &#61; operator.attrgetter(_func_globals)

有关的测试代码&#xff1a;

>>> def boo(a&#61;1):
... x &#61; 100
... b &#61; x - a
... return b

在python2环境中:

>>> boo.__globals__
{&#39;__builtins__&#39;: , &#39;__name__&#39;: &#39;__main__&#39;, &#39;boo&#39;: , &#39;__doc__&#39;: None, &#39;__package__&#39;: None}
>>> boo.func_globals
{&#39;__builtins__&#39;: , &#39;__name__&#39;: &#39;__main__&#39;, &#39;boo&#39;: , &#39;__doc__&#39;: None, &#39;__package__&#39;: None}

在python3环境中:

>>> boo.__globals__
{&#39;__name__&#39;: &#39;__main__&#39;, &#39;__doc__&#39;: None, &#39;__package__&#39;: None, &#39;__loader__&#39;: , &#39;__spec__&#39;: None, &#39;__annotations__&#39;: {}, &#39;__builtins__&#39;: , &#39;boo&#39;: }
>>> boo.func_globals
Traceback (most recent call last):File "", line 1, in
AttributeError: &#39;function&#39; object has no attribute &#39;func_globals&#39;

  • six.next(it) or six.advance_iterator(it)

获取到迭代器的下一个。在python2环境中&#xff0c;使用it.next()&#xff1b;在python3环境中&#xff0c;使用next(it)

try:advance_iterator &#61; next
except NameError:def advance_iterator(it):return it.next()
next &#61; advance_iterator

关于迭代器的内容可以参考一下文件&#xff1a;

  1. 迭代器

在python2环境中&#xff1a;

>>> it &#61; iter([1,2,3,4,5])
>>> while True:
... try:
... x &#61; it.next()
... except NameError:
... print "name error"
... except StopIteration:
... print "end"
... break
...
end>>> it &#61; iter([1,2,3,4,5])
>>> while True:
... try:
... x &#61; next(it)
... except NameError:
... print "name error"
... except StopIteration:
... print "end"
... break
...
end

在python3环境中&#xff1a;

>>> it &#61; iter([1,2,3,4,5])
>>> while True:
... try:
... x &#61; it.next()
... except NameError:
... print("name error")
... except StopIteration:
... print("end")
... break
...
Traceback (most recent call last):File "", line 3, in
AttributeError: &#39;list_iterator&#39; object has no attribute &#39;next&#39;>>> it &#61; iter([1,2,3,4,5])
>>> while True:
... try:
... x &#61; next(it)
... except NameError:
... print("name error")
... except StopIteration:
... print("end")
... break
...
end

  • six.callable(obj)

该方法用来检验obj是否可以进行调用。

关于python的callable属性&#xff0c;请参考一下文件&#xff1a;

  1. python函数每日一讲 - callable(object)

try:callable &#61; callable
except NameError:def callable(obj):return any("__call__" in klass.__dict__ for klass in type(obj).__mro__)

有关的测试代码&#xff1a;

>>> def add(x, y):
... return x &#43; y
...

在python2环境中&#xff1a;

>>> callable(add)
True

在python 3.1环境中&#xff1a;

>>> callable(add)
Traceback (most recent call last):File "", line 1, in
NameError: name &#39;callable&#39; is not defined

在python3.2之后的环境中&#xff1a;

>>> callable(add)
True

来源&#xff1a;https://www.jianshu.com/p/62a6e3f2d1ca


推荐阅读
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • 关键词:Golang, Cookie, 跟踪位置, net/http/cookiejar, package main, golang.org/x/net/publicsuffix, io/ioutil, log, net/http, net/http/cookiejar ... [详细]
  • 本文详细介绍了Java中vector的使用方法和相关知识,包括vector类的功能、构造方法和使用注意事项。通过使用vector类,可以方便地实现动态数组的功能,并且可以随意插入不同类型的对象,进行查找、插入和删除操作。这篇文章对于需要频繁进行查找、插入和删除操作的情况下,使用vector类是一个很好的选择。 ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • 如何自行分析定位SAP BSP错误
    The“BSPtag”Imentionedintheblogtitlemeansforexamplethetagchtmlb:configCelleratorbelowwhichi ... [详细]
  • Commit1ced2a7433ea8937a1b260ea65d708f32ca7c95eintroduceda+Clonetraitboundtom ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 不同优化算法的比较分析及实验验证
    本文介绍了神经网络优化中常用的优化方法,包括学习率调整和梯度估计修正,并通过实验验证了不同优化算法的效果。实验结果表明,Adam算法在综合考虑学习率调整和梯度估计修正方面表现较好。该研究对于优化神经网络的训练过程具有指导意义。 ... [详细]
  • 从零学Java(10)之方法详解,喷打野你真的没我6!
    本文介绍了从零学Java系列中的第10篇文章,详解了Java中的方法。同时讨论了打野过程中喷打野的影响,以及金色打野刀对经济的增加和线上队友经济的影响。指出喷打野会导致线上经济的消减和影响队伍的团结。 ... [详细]
  • 本文介绍了PE文件结构中的导出表的解析方法,包括获取区段头表、遍历查找所在的区段等步骤。通过该方法可以准确地解析PE文件中的导出表信息。 ... [详细]
author-avatar
范大少微博劳
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有