美文网首页
Python3-更多模块

Python3-更多模块

作者: 梦蕊dream | 来源:发表于2018-01-16 10:17 被阅读7次

传递元祖

  • 从一个函数中返回两个不同的值。

代码示例

>>> def detail():
...     return (2,'details')
... 
>>> errnum,errstr = detail()
>>> errnum
2
>>> errstr
'details'

注意a,b = <>这种用法会将表达式解释为具有两个值的元组。

  • 交换两个变量

代码实现

>>> a=3;b=4
>>> a,b
(3, 4)
>>> a,b = b,a
>>> a,b
(4, 3)

特殊方法

  • __init__(self,…)
    新创建对象被返回准备使用时调用
  • __def__(self)
    在对象呗删除之前调用,最好避免使用它
  • __str__(self)
    使用print函数或str()被调用
  • __lt__(self,other)
    当小于运算符(<)使用时被调用.其他运算符也有相对应的特殊方法
  • __getitem__(self,key)
    使用arr[key]索引操作会被调用
  • __len__(self)
    当序列对象使用内置len()函数时被调用

单句语块

代码示例:

>>> flag = True
>>> if flag: print('True')
... 
True

当语句块只包含一句语句时,可以在同行指定,比如条件语句和循环语句.
不建议采用上述方式

Lambda 表格

Lamdba语句可以创建一个新的函数对象.lambda 只需要一个参数,后面跟一个表达式作为函数体,该表达式执行的值将作为新函数的返回值.
示例代码:

points = [{'a':10,'b':11},      
         {'a':9,'b':1}]              
points.sort(key=lambda i:i['b'])
print(points)

输出结果:

[{'a': 9, 'b': 1}, {'a': 10, 'b': 11}]

list 的sort方法可以获取一个"key"参数,用以决定列表排序方式(默认升序).上述方法是根据b 自定义排序.

列表推导

列表推导(List Comprehension)从现有的列表中得到一份新的列表.
代码示例

list = [1,2,3,4]                    
listTwo = [i*2 for i in list if i>2]
print(listTwo)                      

list 中满足i>2,进行操作i*2,获取一份新的列表,原列表保持不变.使用列表推导优点是,当使用循环来处理列表中元素并将其储存在新的列表中,减少代码的数量,方便快捷.

函数接收元组与字典

使用*作为元组的前缀,使用**作为字典的前缀,作为一个参数被函数接收.尤其在函数需要一个可变数量的参数时,尤为有用.
代码示例

# 数组平方求和
def powerSum(power,*arr):
    total = 0
    for i in arr:
        total += pow(i,power)

    return total
print(powerSum(2,4,5))
# 计算 4^2+5^2
print(powerSum(2,10))
# 计算 10^2

输出结果:

41
100

我们再函数参数使用*标记arr变量.调用时除第一位置的参数余下的参数将全部传入arr 中.如果使用**余下参数将被视为字典.

assert 语句

assert 语句用于判断某操作是否为真.如果非真,就抛出一个错误,失败时会抛出AssertionError.
代码示例

>>> print(list)
[1, 2, 3, 4]
>>> assert len(list)>3
>>> assert len(list)>5
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

某些情况下Assert好过异常捕获,也好过定位问题或像用户展示错误信息后退出.灵活使用该语句.

装饰器

装饰器(Decorators)是应用包装函数的快捷方式.有助于把某一功能与某些代码重复"包装".远程计算机进行网络调用的情况十分有用.
示例代码:

from time import sleep
from functools import wraps
import logging
logging.basicConfig()
log = logging.getLogger("retry")

def retry(f):
    @wraps(f)
    def wrap_f(*arr,**dict):
        Max_Attempts = 5
        for item in range(1,Max_Attempts+1):
            try:
                return f(*arr,**dict)
            except:
                log.exception("Attempt %s%s failed:%s",item,Max_Attempts,(arr,dict))
                log.critical("All %s attempts faild :%s",Max_Attempts,(arr,dict))
    return wrap_f()

couter = 0

@retry
def save_database(arr):
    print('=====automactically=====')
    global couter
    couter = couter+1
    # 第一次调用时候抛出异常,第二次运行时正常工作
    if couter < 2:
        raise ValueError(arr)

if __name__ == '__main__':
    save_database('Some bad value')

输出结果:

ERROR:retry:Attempt 15 failed:((), {})
Traceback (most recent call last):
  File "/Users/let/python3/20171213/pyStandradLib.py", line 63, in wrap_f
    return f(*arr,**dict)
TypeError: save_database() missing 1 required positional argument: 'arr'
CRITICAL:retry:All 5 attempts faild :((), {})
ERROR:retry:Attempt 25 failed:((), {})
Traceback (most recent call last):
  File "/Users/let/python3/20171213/pyStandradLib.py", line 63, in wrap_f
    return f(*arr,**dict)
TypeError: save_database() missing 1 required positional argument: 'arr'
CRITICAL:retry:All 5 attempts faild :((), {})
ERROR:retry:Attempt 35 failed:((), {})
Traceback (most recent call last):
  File "/Users/let/python3/20171213/pyStandradLib.py", line 63, in wrap_f
    return f(*arr,**dict)
TypeError: save_database() missing 1 required positional argument: 'arr'
CRITICAL:retry:All 5 attempts faild :((), {})
ERROR:retry:Attempt 45 failed:((), {})
Traceback (most recent call last):
  File "/Users/let/python3/20171213/pyStandradLib.py", line 63, in wrap_f
    return f(*arr,**dict)
TypeError: save_database() missing 1 required positional argument: 'arr'
CRITICAL:retry:All 5 attempts faild :((), {})
ERROR:retry:Attempt 55 failed:((), {})
Traceback (most recent call last):
  File "/Users/let/python3/20171213/pyStandradLib.py", line 63, in wrap_f
    return f(*arr,**dict)
TypeError: save_database() missing 1 required positional argument: 'arr'
CRITICAL:retry:All 5 attempts faild :((), {})
Traceback (most recent call last):
  File "/Users/let/python3/20171213/pyStandradLib.py", line 82, in <module>
    save_database('Some bad value')
TypeError: 'NoneType' object is not callable

原理参考:
https://www.ibm.com/developerworks/linux/library/l-cpdecor/index.html
http://y.tsutsumi.io/dry-principles-through-python-decorators.html

相关文章

  • Python3-更多模块

    传递元祖 从一个函数中返回两个不同的值。 代码示例 注意a,b = <>这种用法会将表达式解释为具有两个值的元组。...

  • Python3-模块

    模块 输出结果: 按字节码编译.pyc 文件 from..import 语句 模块的 name 每个 Python...

  • Python3-模块

    在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护。 为了编写可维护的...

  • Python3-使用模块

    Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用。 我们以内建的sys模块为例,编...

  • 107. mac下pip安装的包路径与各python路径

    1- pip包路径terminal-> python2/python3-> import numpy -> num...

  • Python3-模块(Module) amd 包(Package

    模块(Module):单个Py文件。 导入模块:导入方法1import 模块名1,模块名2,模块名3导入方法2 ...

  • python之datetime模块

    datetime 模块 datatime 模块重新封装了 time 模块,提供了更多接口,变得更加直观和易于调用。...

  • Python3-安装第三方模块

    在Python中,安装第三方模块,是通过包管理工具pip完成的。 如果你正在使用Mac或Linux,安装pip本身...

  • [iOS] 架构之组件化

    首先 组件与模块化概念的正名 从设计上来看,组件强调复用(更多依托技术),模块强调职责(内聚、分离)(更多依托业务...

  • Python时间序列处理模块(datetime模块)

    datatime模块 datatime模块是在time模块的基础之上做了封装,提供了更多更好用的类供我们使用,常用...

网友评论

      本文标题:Python3-更多模块

      本文链接:https://www.haomeiwen.com/subject/ywytoxtx.html