python函数方法语句_python语句函数与方法的使用技巧总结

python语句函数与方法的使用技巧总结

Python 语句、函数与方法的使用技巧总结显示有限的接口到外部当发布 python 第三方 package 时,并不希望代码中所有的函数或者 class 可以被外部 import,在__init__.py 中添加__all__属性,该 list 中填写可以import 的类或者函数名, 可以起到限制的 import 的作用, 防止外部import 其他函数或者类。#!/usr/bin/env python# -*- coding: utf-8 -*-from base import APIBasefrom client import Clientfrom decorator import interface, export, streamfrom server import Serverfrom storage import Storagefrom util import (Logatter, disable_logging_to_stderr, enable_logging_to_kids, info)__all__ = [ APIBase , Client , Logatter , Server , Storage , disable_logging_to_stderr , enable_logging_to_kids , export , info , interface , stream ]with 的魔力with 语句需要支持上下文管理协议的对象, 上下文管理协议包含__enter__和__exit__两个方法。 with 语句建立运行时上下文需要通过这两个方法执行进入和退出操作。其中上下文表达式是跟在 with 之后的表达式, 该表达式返回一个上下文管理对象。# 常见 with 使用场景with open(“test.txt“, “r“) as my_file: # 注意, 是__enter__()方法的返回值赋值给了 my_file,for line in my_file:print line知道具体原理,我们可以自定义支持上下文管理协议的类,类中实现__enter__和__exit__方法。#!/usr/bin/env python# -*- coding: utf-8 -*-class MyWith(object):def __init__(self):print “__init__ “def __enter__(self):print “__enter__ “return self # 返回对象给 as 后的变量def __exit__(self, exc_type, exc_value, exc_traceback):print “__exit__ “if exc_traceback is None:print “Exited without Exception“return Trueelse:print “Exited with Exception“return Falsedef test_with():with MyWith() as my_with:print “running my_with“print “------分割线-----“with MyWith() as my_with:print “running before Exception“raise Exceptionprint “running after Exception“if __name__ == __main__ :test_with()执行结果如下:__init__ __enter__ running my_with__exit__ Exited without Exception------分割线-----__init__ __enter__ running before Exception__exit__ Exited with ExceptionTraceback (most recent call last):File “bin/python“, line 34, in c(compile(__file__f.read(), __file__, “c“))File “test_with.py“, line 33, in test_with()File “test_with.py“, line 28, in test_withraise ExceptionException证明了会先执行__enter__方法, 然后调用 with 内的逻辑, 最后执行__exit__做退出处理, 并且, 即使出现异常也能正常退出filter 的用法相对 filter 而言, map 和 reduce 使用的会更频繁一些, filter 正如其名字, 按照某种规则过滤掉一些元素。#!/usr/bin/env python# -*- coding: utf-8 -*-lst = [1, 2, 3, 4, 5, 6]# 所有奇数都会返回 True, 偶数会返回 False 被过滤掉print filter(lambda x: x % 2 != 0, lst)#输出结果[1, 3, 5]一行作判断当条件满足时, 返回的为等号后面的变量, 否则返回 else 后语句。lst = [1, 2, 3]new_lst = lst[0] if lst is not None else Noneprint new_lst# 打印结果1装饰器之单例使用装饰器实现简单的单例模式# 单例装饰器def singleton(cls):instances = dict() # 初始为空def _singleton(*args, **kwargs):if cls not in instances: #如果不存在, 则创建并放入字典instances[cls] = cls(*args, **kwargs)return instances[cls]return _singleton@singletonclass Test(object):passif __name__ == __main__ :t1 = Test()t2 = Test()# 两者具有相同的地址print t1, t2static 装饰器类中两种常用的装饰, 首先区分一下他们:普通成员函数, 其中第一个隐式参数为对象class 装饰器, 类方法(给人感觉非常类似于 OC 中的类方法), 其中第一个隐式参数为类static 装饰器, 没有任何隐式参数 . python 中的静态方法类似与 C++中的静态方法#!/usr/bin/env python# -*- coding: utf-8 -*-class A(object):# 普通成员函数def foo(self, x):print “cuting foo(%s, %s)“ % (self, x)@classmeth

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值