




已阅读5页,还剩13页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
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 (LogFormatter, disable_logging_to_stderr, enable_logging_to_kids, info)_all_ = APIBase, Client, LogFormatter, Server,Storage, disable_logging_to_stderr, enable_logging_to_kids,export, info, interface, streamwith的魔力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_ method def _enter_(self): print _enter_ method return self # 返回对象给as后的变量 def _exit_(self, exc_type, exc_value, exc_traceback): print _exit_ method if exc_traceback is None: print Exited without Exception return True else: 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 Exception print running after Exceptionif _name_ = _main_: test_with()执行结果如下:_init_ method_enter_ methodrunning my_with_exit_ methodExited without Exception-分割线-_init_ method_enter_ methodrunning before Exception_exit_ methodExited with ExceptionTraceback (most recent call last): File bin/python, line 34, in exec(compile(_file_f.read(), _file_, exec) File test_with.py, line 33, in test_with() File test_with.py, line 28, in test_with raise 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, 3new_lst = lst0 if lst is not None else Noneprint new_lst# 打印结果1装饰器之单例使用装饰器实现简单的单例模式# 单例装饰器def singleton(cls): instances = dict() # 初始为空 def _singleton(*args, *kwargs): if cls not in instances: #如果不存在, 则创建并放入字典 instancescls = cls(*args, *kwargs) return instancescls return _singletonsingletonclass Test(object): passif _name_ = _main_: t1 = Test() t2 = Test() # 两者具有相同的地址 print t1, t2staticmethod装饰器类中两种常用的装饰, 首先区分一下他们:普通成员函数, 其中第一个隐式参数为对象classmethod装饰器, 类方法(给人感觉非常类似于OC中的类方法), 其中第一个隐式参数为类staticmethod装饰器, 没有任何隐式参数. python中的静态方法类似与C+中的静态方法#!/usr/bin/env python# -*- coding: utf-8 -*-class A(object): # 普通成员函数 def foo(self, x): print executing foo(%s, %s) % (self, x) classmethod # 使用classmethod进行装饰 def class_foo(cls, x): print executing class_foo(%s, %s) % (cls, x) staticmethod # 使用staticmethod进行装饰 def static_foo(x): print executing static_foo(%s) % xdef test_three_method(): obj = A() # 直接调用噗通的成员方法 obj.foo(para) # 此处obj对象作为成员函数的隐式参数, 就是self obj.class_foo(para) # 此处类作为隐式参数被传入, 就是cls A.class_foo(para) #更直接的类方法调用 obj.static_foo(para) # 静态方法并没有任何隐式参数, 但是要通过对象或者类进行调用 A.static_foo(para)if _name_ = _main_: test_three_method() # 函数输出executing foo(, para)executing class_foo(, para)executing class_foo(, para)executing static_foo(para)executing static_foo(para)property装饰器定义私有类属性将property与装饰器结合实现属性私有化(更简单安全的实现get和set方法)。#python内建函数property(fget=None, fset=None, fdel=None, doc=None)fget是获取属性的值的函数,fset是设置属性值的函数,fdel是删除属性的函数,doc是一个字符串(像注释一样)。从实现来看,这些参数都是可选的。property有三个方法getter(), setter()和delete() 来指定fget, fset和fdel。 这表示以下这行:class Student(object): property #相当于property.getter(score) 或者property(score) def score(self): return self._score score.setter #相当于score = property.setter(score) def score(self, value): if not isinstance(value, int): raise ValueError(score must be an integer!) if value 100: raise ValueError(score must between 0 100!) self._score = valueiter魔法通过yield和_iter_的结合,我们可以把一个对象变成可迭代的通过_str_的重写, 可以直接通过想要的形式打印对象#!/usr/bin/env python# -*- coding: utf-8 -*-class TestIter(object): def _init_(self): self.lst = 1, 2, 3, 4, 5 def read(self): for ele in xrange(len(self.lst): yield ele def _iter_(self): return self.read() def _str_(self): return ,.join(map(str, self.lst) _repr_ = _str_def test_iter(): obj = TestIter() for num in obj: print num print objif _name_ = _main_: test_iter()神奇partialpartial使用上很像C+中仿函数(函数对象)。在stackoverflow给出了类似与partial的运行方式:def partial(func, *part_args): def wrapper(*extra_args): args = list(part_args) args.extend(extra_args) return func(*args) return wrapper利用用闭包的特性绑定预先绑定一些函数参数,返回一个可调用的变量, 直到真正的调用执行:#!/usr/bin/env python# -*- coding: utf-8 -*-from functools import partialdef sum(a, b): return a + bdef test_partial(): fun = partial(sum, 2) # 事先绑定一个参数, fun成为一个只需要一个参数的可调用变量 print fun(3) # 实现执行的即是sum(2, 3)if _name_ = _main_: test_partial() # 执行结果5神秘evaleval我理解为一种内嵌的python解释器(这种解释可能会有偏差), 会解释字符串为对应的代码并执行, 并且将执行结果返回。看一下下面这个例子:#!/usr/bin/env python# -*- coding: utf-8 -*-def test_first(): return 3def test_second(num): return numaction = # 可以看做是一个sandbox para: 5, test_first : test_first, test_second: test_second def test_eavl(): condition = para = 5 and test_second(test_first) 5 res = eval(condition, action) # 解释condition并根据action对应的动作执行 print resif _name_ = _execexec在Python中会忽略返回值, 总是返回None, eval会返回执行代码或语句的返回值exec和eval在执行代码时, 除了返回值其他行为都相同在传入字符串时, 会使用compile(source, , mode)编译字节码。 mode的取值为exec和eval#!/usr/bin/env python# -*- coding: utf-8 -*-def test_first(): print hellodef test_second(): test_first() print seconddef test_third(): print thirdaction = test_second: test_second, test_third: test_third def test_exec(): exec test_second in actionif _name_ = _main_: test_exec() # 无法看到执行结果getattrgetattr(object, name, default)返回对象的命名属性,属性名必须是字符串。如果字符串是对象的属性名之一,结果就是该属性的值。例如, getattr(x, foobar) 等价于 x.foobar。 如果属性名不存在,如果有默认值则返回默认值,否则触发 AttributeError 。# 使用范例class TestGetAttr(object): test = test attribute def say(self): print test methoddef test_getattr(): my_test = TestGetAttr() try: print getattr(my_test, test) except AttributeError: print Attribute Error! try: getattr(my_test, say)() except AttributeError: # 没有该属性, 且没有指定返回值的情况下 print Method Error!if _name_ = _main_: test_getattr() # 输出结果test attributetest method命令行处理def process_command_line(argv): Return a 2-tuple: (settings object, args list). argv is a list of arguments, or None for sys.argv1:. if argv is None: argv = sys.argv1: # initialize the parser object: parser = optparse.OptionParser( formatter=optparse.TitledHelpFormatter(width=78), add_help_option=None) # define options here: parser.add_option( # customized description; put -help last -h, -help, action=help, help=Show this help message and exit.) settings, args = parser.p
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 咖啡因与氨茶碱中毒的临床护理
- 公民健康教育66条
- 湖南长沙一中2025届高三月考(八)-化学答案
- 2025年小班第一学期班务总结模版
- 伏格特-小柳-原田综合征的临床护理
- 脑蛛网膜炎的临床护理
- 游戏客服工作总结模版
- 狼性管理模式之人力资源培训讲义
- 心衰超滤护理规范与实施要点
- 妊娠合并传染病护理查房
- 粉刷墙面施工协议书
- 辅导机构招聘合同协议
- 青年创新意识的培养试题及答案
- 客运车辆合伙经营合同6篇
- 2025届陕西省安康市高三下学期适应性模拟考试历史试题(原卷版+解析版)
- 2025年四川省成都市青羊区中考二诊化学试题(原卷版+解析版)
- 2025年华侨港澳台生联招考试高考地理试卷试题(含答案详解)
- 【MOOC】软件质量保证-西安交通大学 中国大学慕课MOOC答案
- 中西文化鉴赏智慧树知到期末考试答案章节答案2024年郑州大学
- MSOP(测量标准作业规范)测量SOP
- 基于51单片机的仓库管理系统设计和实现机械自动化专业
评论
0/150
提交评论