【justforme】python查漏补缺

2017-04-17  本文已影响30人  Gunter1993

数据类型(也是对象来的)

整数(0xffe3)、浮点数(1.23e5==1.23*10的5次方)、字符串、True和False(使用and、or、not运算)、None(不等于0)

注意:没有常量(python把全大写变量定义为常量)

数据结构

注意:运算符&交集,|并集

高级特性

注意:可for为Iterable,可next为Iterator,iter(Iterable) == Iterator

函数

面向对象

  def func(self, name):
      print(name)
  # type([class_name],[父类tuple],[键值对:{[类的函数名]:[已定义好的函数名]}])
  h = type('Hello', (object,), {"hello": func})  
  h().hello("Mike")
  # 输出结果:Mike

Exception

多进程与多线程

print('Process-%s start...' % os.getpid())
pid = os.fork()  # 之后的代码分别在当前进程和子进程中执行
if pid == 0:  # 返回0是子进程,父进程返回子进程id
   print('I am child process (%s) and my parent is %s.'
         % (os.getpid(), os.getppid()))
else:
   print('I (%s) just created a child process (%s)' % (os.getpid(), pid))

方式二:使用Process(target=[function],args=[tuple_args])

def run_in_child_process(name):
    if isinstance(name, (str,)):
        print("child process %s is running!" % name)
    else:
        raise TypeError("Name should be str type!")

  child_process_name = 'thread_demo'
  p = Process(target=run_in_child_process, args=  (child_process_name,), name=child_process_name)
  print('process %s will start!' % p.name)
  p.start()
  p.join()
  print('process %s is end!' % p.name)

方式三:启动大量子进程使用pool.apply_async([function],args=[tuple_args])

  def long_time_task(name):
      print('Run task %s (%s)...' % (name, os.getpid()))
      start = time.time()
      time.sleep(random.random() * 3)
      end = time.time()
      print('Task %s runs %0.2f seconds.' % (name, (end - start)))
  
  if __name__ == '__main__':
      print('Parent process %s.' % os.getpid())
      p = Pool(4)  # 这里设置同时执行的进程数量为4,默认为cpu核数
      for i in range(5):
          p.apply_async(long_time_task, args=(i,))
      print('Waiting for all subprocesses done...')
      p.close()
      p.join()  # 调用join之前必须close
      print('All subprocesses done.')
  balance = 0

  def change_it(n):
    # 先存后取,结果应该为0:
    global balance
    balance = balance + n
    balance = balance - n

  lock = threading.Lock()

  def run_thread(n):
    for i in range(100000):
      # 先要获取锁:
      lock.acquire()
      try:
        # 放心地改吧:
        change_it(n)
      finally:
        # 改完了一定要释放锁:
        lock.release()

补充

bytes object

b = b"example"

str object

s = "example"

str to bytes

bytes(s, encoding = "utf8")

bytes to str

str(b, encoding = "utf-8")

an alternative method

str to bytes

str.encode(s)

bytes to str

bytes.decode(b)

另外,拼接字符串可以使用str.join(str_list)

上一篇 下一篇

猜你喜欢

热点阅读