• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > 一波神奇的Python语句、函数与方法的使用技巧总结

一波神奇的Python语句、函数与方法的使用技巧总结

作者: 字体:[增加 减小] 来源:互联网

通过本文主要向大家介绍了勇士双星暴走一波屠城,一波,闹一波大师,一波说,神多一波花影音先锋等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

显示有限的接口到外部
当发布python第三方package时,并不希望代码中所有的函数或者class可以被外部import,在__init__.py中添加__all__属性,该list中填写可以import的类或者函数名, 可以起到限制的import的作用, 防止外部import其他函数或者类。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from base import APIBase
from client import Client
from decorator import interface, export, stream
from server import Server
from storage import Storage
from 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', 'stream']
</div>

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

</div>

知道具体原理,我们可以自定义支持上下文管理协议的类,类中实现__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 False
def 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 Exception"
if __name__ == '__main__':
  test_with()
</div>

执行结果如下:

__init__ method
__enter__ method
running my_with
__exit__ method
Exited without Exception
------分割线-----
__init__ method
__enter__ method
running before Exception
__exit__ method
Exited with Exception
Traceback (most recent call last):
 File "bin/python", line 34, in <module>
  exec(compile(__file__f.read(), __file__, "exec"))
 File "test_with.py", line 33, in <module>
  test_with()
 File "test_with.py", line 28, in test_with
  raise Exception
Exception
</div>

证明了会先执行__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]
</div>

一行作判断
当条件满足时, 返回的为等号后面的变量, 否则返回else后语句。

lst = [1, 2, 3]
new_lst = lst[0] if lst is not None else None
print new_lst
# 打印结果
1
</div>

装饰器之单例
使用装饰器实现简单的单例模式

# 单例装饰器
def singleton(cls):
  instances = dict() # 初始为空
  def _singleton(*args, **kwargs):
    if cls not in instances: #如果不存在, 则创建并放入字典
      instances[cls] = cls(*args, **kwargs)
    return instances[cls]
  return _singleton
@singleton
class Test(object):
  pass
if __name__ == '__main__':
  t1 = Test()
  t2 = Test()
  # 两者具有相同的地址
  print t1, t2
</div>

staticmethod装饰器
类中两种常用的装饰, 首先区分一下他们:

普通成员函数, 其中第一个隐式参数为对象

  • 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)" % x
def 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(<__main__.A object at 0x100ba4e10>, para)
executing class_foo(<class '__main__.A'>, para)
executing class_foo(<class '__main__.A'>, para)
executing static_foo(para)
executing static_foo(para)

</div>

property装饰器
定义私有类属性
将property与装饰器结合实现属性私有化(更简单安全的实现get和set方法)。

#python内建函数
property(fget=None, fset=None, fdel=None, doc=None)
</div>

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 < 0 or value > 100:
      raise ValueError('score must between 0 ~ 100!')
    self._score = value
</div>

iter魔法
通过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 obj
if __name__ == '__main__':
  test_iter()
</div>

神奇partial
partial使用上很像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
</div>

利用用闭包的特性绑定预先绑定一些函数参数,返回一个可调用的变量, 直到真正的调用执行:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
from functools import partial
def sum(a, b):
  return a + b
def test_partial():
  fun = partial(sum, 2)  # 事先绑定一个参数, fun成为一个只需要一个参
  


 

您可能想查找下面的文章:

  • 一波神奇的Python语句、函数与方法的使用技巧总结
  • 一波神奇的Python语句、函数与方法的使用技巧总结

相关文章

  • Python利用operator模块实现对象的多级排序详解
  • Python中函数的参数传递与可变长参数介绍
  • Python3连接MySQL(pymysql)模拟转账实现代码
  • Python入门篇之条件、循环
  • 关于tf.nn.dynamic_rnn返回值详解
  • Python使用py2exe打包程序介绍
  • Python求算数平方根和约数的方法汇总
  • python分析网页上所有超链接的方法
  • Python的组合模式与责任链模式编程示例
  • python标准日志模块logging的使用方法

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • 基于scrapy实现的简单蜘蛛采集程序
    • python清除字符串里非数字字符的方法
    • C#返回当前系统所有可用驱动器符号的方法
    • python中的一些类型转换函数小结
    • Python 常用string函数详解
    • 整理Python中的赋值运算符
    • Python时间的精准正则匹配方法分析
    • Python中bisect的用法
    • python虚拟环境virualenv的安装与使用
    • python中的五种异常处理机制介绍

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有