• Pythonic 的代码编写方法


    1.模块导入

    你是不是经常对调用模块时输入一长串模块索引感到头疼?说实在的,数量少的时候或许还可以勉强忍受,一旦程序规模上去了,这也是一项不容小觑的工程

    #Bad
    
    import urllib.request
    
    url = r'http://www.baidu.com'
    
    req = urllib.request.Request(url)
    
    response = urllib.request.urlopen(req)
    
    #Good
    
    from urllib import request 
    
    url = r'http://www.baidu.com'
    
    req = request.Request(url)
    
    response = request.urlopen(req)

     如果遇到不同package中重复的模块,我们如何区分呢?,示例如下:

    from module_a import fun as a_fun
    from module_b import fun as b_fun
    

     这样的方式还适合模块名比较长的方法,举例如下:

    from bs4 import BeautifulSoup as BS
    
    html = '''
           <html>
                ......
           </html>
           '''
    soup = BS(html)

    2.关于 "_" ##

    这是一个非常有用的功能,可惜很少人知道。

    当你在交互界面敲代码,获得一个临时结果,却没有用变量名去保存它的时候,可以用"_"来获取最近一次临时结果。

    >>> 3*5
    15
    >>> _
    15

    在"_"中存储最后输出的值。这在交互式模式中是非常有用的,当你在过程中没有保存计算结果,或者你想看最后一步执行的输出结果。

    3.合并字符串

    直接用+ 号比用''.join方法更占用内存资源

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #  Author: Jason Wang
    
    
    # Bad
    string = ['a','b','c','d','e','f','g','h','ss']
    
    def fun(string):
        all_string = ''
        for i in string:
            all_string += i
        return all_string
    
    
    # Good
    string = ['a','b','c','d','e','f','g','h'.'ss']
    
    def fun(string):
        all_string = ''.join(string)
        return all_string

    4.强大的zip()

    它是Python的内建函数,zip函数接受任意多个(包括0个和1个)序列作为参数,返回一个包含tuple的list。zip()函数可以在很多场景简化你的代码。

    矩阵的行列互换

    ##bad
    >>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] >>> re_a = [[row[col] for row in a] for col in range(len(a))] >>> re_a [[1, 4, 7], [2, 5, 8], [3, 6, 9]]
    ##good >>> re_a = list(zip(*a)) >>> re_a [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

    交换dict的键值

    ##bad
    >>> a = {'a':1, 'b':2, 'c':3, 'd':4}
    >>> def reve_dict(a):
    ...     new_dict = {}
    ...     for k,v in a.items():
    ...         new_dict[v] = k
    ...     return new_dict
    ...     
    >>> reve_dict(a)
    {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
    ##good
    >>> def reve_dict2(a):
    ...     k = a.keys()
    ...     v = a.values()
    ...     new_dict = dict(zip(v,k))
    ...     return new_dict
    ...     
    >>> reve_dict2(a)
    {1: 'a', 2: 'b', 3: 'c', 4: 'd'}

    合并list相邻项

    >>> a = [1, 2, 3, 4, 5, 6]
    >>> a[::2]
    [1, 3, 5]
    >>> a[1::2]
    [2, 4, 6]
    >>> list(zip(a[::2],a[1::2]))
    [(1, 2), (3, 4), (5, 6)]
    >>> a = list(zip(a[::2],a[1::2]))
    >>> a
    [(1, 2), (3, 4), (5, 6)]

    5.变量值交换

    # Bad
    tmp = a
    a = b
    b = tmp
    
    #Good
    a, b = b, a

    6.在循环中获取索引(数组下标)?

    >>> a = [8,12,45,33,8]
    >>> for index, value in enumerate(a):
    ...     print(index,value)
    ...     
    0 8
    1 12
    2 45
    3 33
    4 8

    7.如何在只用一行捕获多个异常?

    try:
        pass
    except (ExceptionA,ExceptionB,.....) as e:
        pass

    8.把列表分割成同样大小的块

    >>> a
    [8, 12, 45, 33, 8]
    >>> list(zip( *[iter(a)]*2))
    [(8, 12), (45, 33)]

    9.如何查找列表中某个元素的下标?

    a = ['a', 'b', 'c', 'd', 'e', 'f']
    
    a_i = a.index(a)
    >>> 0 
    

    10.如何快速反转字符串?

    ##bad

    >>> a = 'python reverse method'
    >>> list_a = list(a)
    >>> list_a.reverse()
    >>> re_a = ''.join(list_a)
    >>> re_a
    'dohtem esrever nohtyp'

    ##good

    >>> a = 'python reverse method'
    >>> re_a = a[::-1]
    >>> re_a
    'dohtem esrever nohtyp'

     

     11. 用with打开文件

    平时在使用类似文件的流对象时,使用完毕后要调用close方法关闭。with…as语句提供了一个非常方便的替代方法:open打开文件后将返回的文件流对象赋值给f,然后在with语句块中使用。with语句块完毕之后,会隐藏地自动关闭文件。

    with open('foo.txt','r') as f:
        f.read()

    with 魔法方法内部实现原理:

    with语句需要支持上下文管理协议的对象, 上下文管理协议包含 __enter__ 和 __exit__ 两个方法. with语句建立运行时上下文需要通过这两个方法执行进入和退出操作.

    其中上下文表达式是跟在with之后的表达式, 该表达示返回一个上下文管理对象

    知道具体原理, 我们可以自定义支持上下文管理协议的类, 类中实现 __enter__ 和 __exit__ 方法

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #  Author: Jason Wang
    
    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()

    执行结果如下:

    __init__ method
    __enter__ method
    running my_with
    __exit__ method
    Exited without Exception
    ------分割线-----
    __init__ method
    __enter__ method
    running before Exception
    __exit__ method
    Traceback (most recent call last):
    Exited with Exception
      File "/Users/JasonWang/PycharmProject/spider/mywith.py", line 28, in <module>
        test_with()
      File "/Users/JasonWang/PycharmProject/spider/mywith.py", line 25, in test_with
        raise Exception
    Exception

    证明了会先执行 __enter__ 方法, 然后调用with内的逻辑, 最后执行 __exit__ 做退出处理, 并且, 即使出现异常也能正常退出

    12.和你的内存说再见

    crash = dict(zip(range(10 **0xA), range(10 **0xA)))
    ##说明
    range(10 **0xA)
    >>> range(0, 10000000000)
    用range()生成,不会抛MemoryError,然后进行压缩,再转换成dict,内存很快会消耗干净的,电脑就一动不动了......
    

    13.显示有限的接口到外部

    当发布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']
    

     14.filter的用法

    相对filter而言, map和reduce使用的会更频繁一些, filter正如其名字, 按照某种规则过滤掉一些元素

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #  Author: Jason Wang
    
    lst = [1,2,3,4,5]
    # 所有奇数都会返回True, 偶数会返回False被过滤掉
    f_list =filter(lambda x:x % 2 !=0,lst)
    
    print(list(f_list))

    15.一行作判断

    当条件满足时, 返回的为等号后面的变量, 否则返回else后语句

    >>> lst = [4,5,6]
    >>> new_l =lst[1] if lst is not None else None
    >>> new_l
    5
    

     16.用装饰器实现单例模式

    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__':
        tt1 = Test()
        tt2 = Test()
        print(tt1,tt2)

    staticmethod装饰器

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

    • 普通成员函数, 其中第一个隐式参数为对象
    • classmethod装饰器, 类方法(给人感觉非常类似于OC中的类方法), 其中第一个隐式参数为
    • staticmethod装饰器, 没有任何隐式参数. python中的静态方法类似与C++中的静态方法
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #  Author: Jason Wang
    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 0x1029ef278>, para)
    # executing class_foo(<class '__main__.A'>, para)
    # executing class_foo(<class '__main__.A'>, 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是一个字符串(like a comment).从实现来看,这些参数都是可选的

    property有三个方法getter()setter()delete() 来指定fget, fset和fdel。 这表示以下这行

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #  Author: Jason Wang
    
    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

    17.iter魔法

    • 通过yield和__iter__的结合, 我们可以把一个对象变成可迭代的
    • 通过__str__的重写, 可以直接通过想要的形式打印对象
    class MyIter():
        def __init__(self):
            self.lst = [1, 2, 3, 4, 5]
        def read(self):
            for ele in range(len(self.lst)):
                yield ele
        def __iter__(self):
            return self.read()
        def __str__(self):
            return ','.join(map(str, self.lst))
    
        __repr__ = __str__
    def t_iter():
        obj = MyIter()
        for num in obj:
            print(num)
        print(obj)
    if __name__ == '__main__':
        t_iter()
    ##result
    0
    1
    2
    3
    4
    1,2,3,4,5

    18.神奇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

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

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #  Author: Jason Wang
    
    def partial(func, *part_args):
        def wrapper(*extra_args):
            args = list(part_args)
            args.extend(extra_args)
            return func(*args)
        return wrapper
    
    
    from functools import partial
    def sum(a, b):
        return a + b
    def test_partial():
        fun = partial(sum, 2)   # 事先绑定一个参数, fun成为一个只需要一个参数的可调用变量
        print(fun(3))  # 实现执行的即是sum(2, 3)
    if __name__ == '__main__':
        test_partial()
        
    ##执行结果:
    5

    19.神秘eval,exec

    eval我理解为一种内嵌的python解释器(这种解释可能会有偏差), 会解释字符串为对应的代码并执行, 并且将执行结果返回

    看一下下面这个例子

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #  Author: Jason Wang
    
    
    def test_first():
        return 3
    def test_second(num):
        return num
    action = {  # 可以看做是一个sandbox
            "para": 6,
            "test_first" : test_first,
            "test_second": test_second,
            }
    def test_eavl():
        condition = "para == 6 and test_second(test_first()) < 5"
        res = eval(condition, action)  # 解释condition并根据action对应的动作执行
        print(res)
    if __name__ == '__main__':
        test_eavl()
    ##result
    True

    exec

    • exec在Python中会忽略返回值, 总是返回None, eval会返回执行代码或语句的返回值
    • execeval在执行代码时, 除了返回值其他行为都相同
    • 在传入字符串时, 会使用compile(source, '<string>', mode)编译字节码. mode的取值为execeval
    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #  Author: Jason Wang
    
    def test_first():
        print("hello")
    def test_second():
        test_first()
        print("second")
    def test_third():
        print("third")
    action = {
            "test_second": test_second,
            "test_third": test_third
            }
    def test_exec():
        exec("test_second()") in action
    if __name__ == '__main__':
        test_exec()  # 无法看到执行结果
    ##
    hello
    second

    20.getattr

    getattr

    getattr(object, name[, default])Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object’s attributes, the result is the value of that attribute. For example, getattr(x, ‘foobar’) is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.

    通过string类型的name, 返回对象的name属性(方法)对应的值, 如果属性不存在, 则返回默认值, 相当于object.name

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #  Author: Jason Wang
    
    # 使用范例
    class MyGetAttr(object):
        test = "test attribute"
        def say(self):
            print("test method")
    def my_getattr():
        my_test = MyGetAttr()
        try:
            print(getattr(my_test, "test"))
        except AttributeError:
            print("Attribute Error!")
        try:
            getattr(my_test, "say")()
        except AttributeError: # 没有该属性, 且没有指定返回值的情况下
            print("Method Error!")
    if __name__ == '__main__':
        my_getattr()
    ##
    test attribute
    test method

    命令行处理

    #!/usr/bin/env python
    # -*- coding:utf-8 -*-
    #  Author: Jason Wang
    import sys
    import optparse
    def process_command_line(argv):
        """
        Return a 2-tuple: (settings object, args list).
        `argv` is a list of arguments, or `None` for ``sys.argv[1:]``.
        """
        if argv is None:
            argv = sys.argv[1:]
            print(argv)
        # 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.parse_args(argv)
        # check number of arguments, verify values, etc.:
        if args:
            parser.error('program takes no command-line arguments; '
                         '"%s" ignored.' % (args,))
        # further process settings & args if necessary
        return settings, args
    def main(argv=None):
        settings, args = process_command_line(argv)
        print('settings:',settings,'arg:',args)
        # application code here, like:
        # run(settings, args)
        return 0        # success
    if __name__ == '__main__':
        status = main()
        print(status)
        sys.exit(status)

    读写csv文件

    # 从csv中读取文件, 基本和传统文件读取类似
    import csv
    with open('data.csv', 'rb') as f:
        reader = csv.reader(f)
        for row in reader:
            print row
    # 向csv文件写入
    import csv
    with open( 'data.csv', 'wb') as f:
        writer = csv.writer(f)
        writer.writerow(['name', 'address', 'age'])  # 单行写入
        data = [
                ( 'xiaoming ','china','10'),
                ( 'Lily', 'USA', '12')]
        writer.writerows(data)  # 多行写入

    各种时间形式转换

    只发一张网上的图, 然后差文档就好了, 这个是记不住的

    字符串格式化

    一个非常好用, 很多人又不知道的功能

    >>> name = 'Jason'
    >>> 'my name is {name}'.format(name=name)
    'my name is Jason'
  • 相关阅读:
    jFinal基于maven简单的demo
    quartz定时任务
    cors解决跨越问题
    poi导出excel
    layui富文本编译器后台获取图片路径
    HttpClient短信接口
    js分页
    El表达式日期处理
    【传智播客】Libevent学习笔记(二):创建event_base
    【传智播客】Libevent学习笔记(一):简介和安装
  • 原文地址:https://www.cnblogs.com/jasonwang-2016/p/6144886.html
Copyright © 2020-2023  润新知