Python拾遗(持续更新中)

本篇博文将会持续更新,不断加入本人遗漏的Python知识点

4月5日~4月10日:

  • 在Linux下,使用
#!/usr/bin/python3
或者
#!/usr/bin/env python3

来指定改Python程序运行时使用的python版本

  • 使用 type(变量名) 查询变量类型。存在 type(a) == str 这种用法。
  • 使用 id(变量名) 查询变量在Python解释器中被分配的地址。
  • 使用 dir(变量名) 查询该变量的成员。
  • //用作除法运算符,获得结果的整数部分。

4月11日~4月17日:

  • 有关str的方法:
  1. __contains__相当于in
  2. 输出多个重复字符
    print(8*'*')
    ********
  3. center
    >>> "hello".center(10, '-')
    '--hello---'
  4. find与index区别
    >>> "hello".find('x')
    -1
    >>> "hello".index('x')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: substring not found
  5. format
    >>> "hello {0} and {1}".format("one", "two")
    'hello one and two'
    >>> "hello {name1} and {name2}".format(name1="one", name2="two")
    'hello one and two'
  • 养成tuple末尾带逗号的习惯
    >>> {2,3,}
    {2, 3}
  • dictionary用[]取到不存在的key时会报错,但用get会返回None,并且可以设置默认返回值
    >>> {1:'a',2:'b'}[3]
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    KeyError: 3
    >>> {1:'a',2:'b'}.get(3, 'c')
    'c'

4月18日~4月24日:

  • 修改浅拷贝的对象(数字,字符除外)将会改变原对象
  • 函数没有return语句将返回None
  • 使用bool()来检查某个变量是否是真
    >>> bool(None)
    False
    >>> bool(0)
    False
    >>> bool(3)
    True
    >>> bool("")
    False
    >>> bool([])
    False
    >>> bool({})
    False
  • Python Collections:
    • Counter,对字典的补充
      >>> import collections
      >>> collections.Counter([1,2,3,4,5,5,4])
      Counter({4: 2, 5: 2, 1: 1, 2: 1, 3: 1})
    • OrderedDict,保留key插入顺序的有序字典
      >>> dict = collections.OrderedDict()
      >>> dict['b'] = 2
      >>> dict['a'] = 1
      >>> dict['c'] = 3
      >>> dict
      OrderedDict([('b', 2), ('a', 1), ('c', 3)])
    • defaultdict,可设置字典value的默认类型
      >>> dict = collections.defaultdict(list)
      >>> dict['anyKey']
      []
    • namedtuple
      >>> Point = collections.namedtuple('Point', ['x', 'y'])
      >>> point = Point(2, 3)
      >>> point
      Point(x=2, y=3)
      >>> point.x
      2
      >>> point.y
      3
    • deque,线程安全双向队列
  • Queue,单向队列
    >>> import queue
    >>> queue.Queue()
    <queue.Queue object at 0x101c3a630>
  • 动态参数
    • 一个*的情况
      >>> def show(*args):
      ...     print(args)
      ...
      >>> show(3)
      (3,)
      >>> show(3, 2, 4, 1)
      (3, 2, 4, 1)
      >>> l = [3, 2, 1]
      >>> show(l)
      ([3, 2, 1],)
      >>> show(*l)
      (3, 2, 1)
    • 二个*的情况,在字符串的格式化函数format中使用到。
      >>> def doubleStart(**args):
      ...     print(args)
      ...
      >>> doubleStart(name1="x", name2="y")
      {'name1': 'x', 'name2': 'y'}
      >>> dict = {"name3":"z", "name4":"a"}
      >>> doubleStart(**dict)
      {'name4': 'a', 'name3': 'z'}
    • *与**混合的情况,*只能出现在**前
      >>> def stars(*args, **kwargs):
      ...     print(args)
      ...     print(kwargs)
      ...
      >>> stars(1, 2, 3, name1="x", name2="y")
      (1, 2, 3)
      {'name1': 'x', 'name2': 'y'}
      >>> l
      [3, 2, 1]
      >>> dict
      {'name4': 'a', 'name3': 'z'}
      >>> stars(*l, **dict)
      (3, 2, 1)
      {'name4': 'a', 'name3': 'z'}
  • enumerate,方便地给出了循环index
    >>> l
    [3, 2, 1]
    >>> for i, item in enumerate(l, 10):
    ...     print(i, item)
    ...
    10 3
    11 2
    12 1

4月25日~5月8日:本期金角相关博客

  • 快速生成列表方式
  • >>> data = [[col for col in range(4)] for row in range(3)]
    >>> data
    [[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]
    >>> print(data)
  •  正则表达式(match, findall, search, sub)

    • match从开头匹配
      >>> res = re.match('[0-9]{0,4}', '1234abc123')
      >>> print(res.group())
      1234
      

        

5月9日~5月15日:本期金角相关博文

  • 下载安装开源模块
    • pip
    • yum
    • apt-get
    • 下载源码后,运行python setup.py install,需要安装python-dev 
  •  Alex的自定义模块的例子

目录结构如下:

----dj

--------__init__.py

--------user_main.py

--------backend

----------------db

--------------------__init__.py

--------------------sql_api.py

----------------logic

--------------------__init__.py

--------------------handle.py

--------frontend

--------config

----------------__init__.py

----------------settings.py

 user_main.py中的函数,调用了handle.py中的函数。handle.py中的函数调用了sql_api.py中的函数。sql_api.py中的函数使用了settings.py中的数据。

  • 打印当前文件相对路径
    print(__file__)

     

  • 打印当前文件绝对路径
    import os
    print(os.path.abspath(__file__))
  • 添加文件查找路径
    import sys
    sys.path.append(dir)
  • 找到父目录
    os.path.dirname(os.path.abspath(__file__))
  • pickle与json区别。前者存为binary,后者是字符串。前者是Python独有支持的格式,可序列化任何Python类型。可用于游戏保存。

    • dump包含了dumps步骤与文件写入步骤。load包含了loads与文件读取步骤。

5月16日~5月22日:金角关于面向对象的博文银角关于面向对象进阶的博文

  • 使用shutil进行文件操作
    >>> import shutil
    >>> shutil.copyfile("test.js", "test2.js")
    'test2.js'
  • 使用subprocess替代os.system, os.spawn
    • 在2.7中,subprocess调用call方法运行系统命令。
      • 若命令带有参数,则需要将命令名称与参数放在一个列表中
        subprocess.call(["ls", "-al"])
      • 或者用原生的shell  
        subprocess.run("ls -al", shell=True)
      • 当需要获取命令运行的结果时,使用
        >>> import subprocess
        >>> result = subprocess.Popen("ls -al", shell=True, stdout=subprocess.PIPE)
        >>> result.stdout.read()
      • 使用subprocess.check_call检查异常
      • 与子进程对话
        >>> pipe = subprocess.Popen(["Python"], stdin = subprocess.PIPE, stdout = subprocess.PIPE)
        >>> pipe.stdin.write('print "hello"')
        >>> output = pipe.communicate(timeout=10)
        Traceback (most recent call last):
          File "<stdin>", line 1, in <module>
        TypeError: communicate() got an unexpected keyword argument 'timeout'
        >>> output = pipe.communicate()
        >>> print output
        ('hello
        ', None)
        >>>
    • 在3中,subprocess调用run方法运行系统命令。
      subprocess.run(["ls", "-al"])
  • 在类的外面对__XXX赋值,不影响类内部的__XXX的值。
  • Python3中继承多个类时,函数的调用以广度优先为原则。
  • Python2中经典类为深度优先,新式类为广度优先。
  • hasattr与getattr共同使用实现反射。还有setattr(绑定方法到实例上),deleteattr(方法属于类,需要通过类删除)。

5月30日~6月5日: 金角博文地址银角博文地址

  • 判断是否是某个类的实例:isinstance(a, list)等价于type(a) == list
  • issubclass(a, b)
  • threading,直接调用与继承调用例子,sleep与操作IO的时候进行切换
    import threading
    import time
     
    def sayhi(num): #定义每个线程要运行的函数
     
        print("running on number:%s" %num)
     
        time.sleep(3)
     
    if __name__ == '__main__':
     
        t1 = threading.Thread(target=sayhi,args=[1,]) #生成一个线程实例
        t2 = threading.Thread(target=sayhi,args=[2,]) #生成另一个线程实例
     
        t1.start() #启动线程
        t2.start() #启动另一个线程
     
        print(t1.getName()) #获取线程名
        print(t2.getName())
    import threading
    import time
     
     
    class MyThread(threading.Thread):
        def __init__(self,num):
            threading.Thread.__init__(self)
            self.num = num
     
        def run(self):#定义每个线程要运行的函数
     
            print("running on number:%s" %self.num)
     
            time.sleep(3)
     
    if __name__ == '__main__':
     
        t1 = MyThread(1)
        t2 = MyThread(2)
        t1.start()
        t2.start()
    t2.join()
  • deamon例子
    import time
    import threading
     
    def run(n):
     
        print('[%s]------running----
    ' % n)
        time.sleep(2)
        print('--done--')
     
    def main():
        for i in range(5):
            t = threading.Thread(target=run,args=[i,])
            #time.sleep(1)
            t.start()
            t.join(1)
            print('starting thread', t.getName())
     
     
    m = threading.Thread(target=main,args=[])
    m.setDaemon(True) #将主线程设置为Daemon线程,它退出时,其它子线程会同时退出,不管是否执行完任务
    m.start()
    #m.join(timeout=2)
    print("---main thread done----")
  • 互斥锁
    lock.acquire() #修改数据前加锁
    num  -=1 #对此公共变量进行-1操作
    lock.release() #修改后释放
     
    num = 100  #设定一个共享变量
    thread_list = []
    lock = threading.Lock() #生成全局锁
  • Event
  • event = threading.Event()
    
    # a client thread can wait for the flag to be set
    event.wait()
    
    # a server thread can set or reset it
    event.set()
    event.clear()
  • 多进程例子,父子进程之间进行通讯可以将父进程的数据当做变量传入子进程,比如使用Queue,pipe不常用:
    from multiprocessing import Process
    import time
    def f(name):
        time.sleep(2)
        print('hello', name)
     
    if __name__ == '__main__':
        p = Process(target=f, args=('bob',))
        p.start()
        p.join()
  • Pool, 同步时不能有callback,异步时才能有。Windows下需要使用freeze_support()。
原文地址:https://www.cnblogs.com/bettybear/p/5380011.html