python实用代码片段收集贴

   这篇文章主要介绍了python实用代码片段收集贴,本文收集了如获取一个类的所有子类、计算运行时间、SQLAlchemy简单使用、实现类似Java或C中的枚举等实用功能代码,需要的朋友可以参考下

  获取一个类的所有子类

  复制代码 代码如下:

  def itersubclasses(cls, _seen=None):

  """Generator over all subclasses of a given class in depth first order."""

  if not isinstance(cls, type):

  raise TypeError(_('itersubclasses must be called with '

  'new-style classes, not %.100r') % cls)

  _seen = _seen or set()

  try:

  subs = cls.__subclasses__()

  except TypeError: # fails only when cls is type

  subs = cls.__subclasses__(cls)

  for sub in subs:

  if sub not in _seen:

  _seen.add(sub)

  yield sub

  for sub in itersubclasses(sub, _seen):

  yield sub

  简单的线程配合

  复制代码 代码如下:

  import threading

  is_done = threading.Event()

  consumer = threading.Thread(

  target=self.consume_results,

  args=(key, self.task, runner.result_queue, is_done))

  consumer.start()

  self.duration = runner.run(

  name, kw.get("context", {}), kw.get("args", {}))

  is_done.set()

  consumer.join() #主线程堵塞,直到consumer运行结束

  多说一点,threading.Event()也可以被替换为threading.Condition(),condition有notify(), wait(), notifyAll()。解释如下:

  复制代码 代码如下:

  The wait() method releases the lock, and then blocks until it is awakened by a notify() or notifyAll() call for the same condition variable in another thread. Once awakened, it re-acquires the lock and returns. It is also possible to specify a timeout.

  The notify() method wakes up one of the threads waiting for the condition variable, if any are waiting. The notifyAll() method wakes up all threads waiting for the condition variable.

  Note: the notify() and notifyAll() methods don't release the lock; this means that the thread or threads awakened will not return from their wait() call immediately, but only when the thread that called notify() or notifyAll() finally relinquishes ownership of the lock.

  复制代码 代码如下:

  # Consume one item

  cv.acquire()

  while not an_item_is_available():

  cv.wait()

  get_an_available_item()

  cv.release()

  # Produce one item

  cv.acquire()

  make_an_item_available()

  cv.notify()

  cv.release()

  计算运行时间

  复制代码 代码如下:

  class Timer(object):

  def __enter__(self):

  self.error = None

  self.start = time.time()

  return self

  def __exit__(self, type, value, tb):

  self.finish = time.time()

  if type:

  self.error = (type, value, tb)

  def duration(self):

  return self.finish - self.start

  with Timer() as timer:

  func()

  return timer.duration()

  元类

  __new__()方法接收到的参数依次是:

  当前准备创建的类的对象;

  类的名字;

  类继承的父类集合;

  类的方法集合;

  复制代码 代码如下:

  class ModelMetaclass(type):

  def __new__(cls, name, bases, attrs):

  if name=='Model':

  return type.__new__(cls, name, bases, attrs)

  mappings = dict()

  for k, v in attrs.iteritems():

  if isinstance(v, Field):

  print('Found mapping: %s==>%s' % (k, v))

  mappings[k] = v

  for k in mappings.iterkeys():

  attrs.pop(k)

  attrs['__table__'] = name # 假设表名和类名一致

  attrs['__mappings__'] = mappings # 保存属性和列的映射关系

  return type.__new__(cls, name, bases, attrs)

  class Model(dict):

  __metaclass__ = ModelMetaclass

  def __init__(self, **kw):

  super(Model, self).__init__(**kw)

  def __getattr__(self, key):

  try:

  return self[key]

  except KeyError:

  raise AttributeError(r"'Model' object has no attribute '%s'" % key)

  def __setattr__(self, key, value):

  self[key] = value

  def save(self):

  fields = []

  params = []

  args = []

  for k, v in self.__mappings__.iteritems():

  fields.append(v.name)

  params.append('?')

  args.append(getattr(self, k, None))

  sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fields), ','.join(params))

  print('SQL: %s' % sql)

  print('ARGS: %s' % str(args))

  class Field(object):

  def __init__(self, name, column_type):

  self.name = name

  self.column_type = column_type

  def __str__(self):

  return '<%s:%s>

时间: 2024-08-03 12:43:59

python实用代码片段收集贴的相关文章

php实用代码片段整理_php技巧

本文整理归纳了php实用代码片段.分享给大家供大家参考,具体如下: 一 从网页中提取关键词 $meta = get_meta_tags('http://www.jb51.net/'); $keywords = $meta['keywords']; // Split keywords $keywords = explode(',', $keywords ); // Trim them $keywords = array_map( 'trim', $keywords ); // Remove emp

必须收藏的php实用代码片段_php技巧

在编写代码的时候有个神奇的工具总是好的!下面这里收集了 40+ PHP 代码片段,可以帮助你开发PHP 项目. 之前已经为大家分享了<必须收藏的23个php实用代码片段>. 这些PHP 片段对于PHP 初学者也非常有帮助,非常容易学习,让我们开始学习吧- 24. 从 PHP 数据创建 CSV 文件 function generateCsv($data, $delimiter = ',', $enclosure = '"') { $handle = fopen('php://temp'

必须收藏的23个php实用代码片段_php技巧

在编写代码的时候有个神奇的工具总是好的!下面这里收集了 40+ PHP 代码片段,可以帮助你开发 PHP 项目. 这些 PHP 片段对于 PHP 初学者也非常有帮助,非常容易学习,让我们开始学习吧- 1. 发送 SMS 在开发 Web 或者移动应用的时候,经常会遇到需要发送 SMS 给用户,或者因为登录原因,或者是为了发送信息.下面的 PHP 代码就实现了发送 SMS 的功能. 为了使用任何的语言发送 SMS,需要一个 SMS gateway.大部分的 SMS 会提供一个 API,这里是使用 M

【经典源码收藏】jQuery实用代码片段(筛选,搜索,样式,清除默认值,多选等)_jquery

本文实例总结了jQuery实用代码片段.分享给大家供大家参考,具体如下: //each遍历文本框 清空默认值 $(".maincenterul1").find("input,textarea").each(function () { //保存当前文本框的值 var vdefault = this.value; $(this).focus(function () { if (this.value == vdefault) { this.value = "&q

一些实用的jQuery代码片段收集_jquery

下边这些jQuery片段只是很少的一部分,如果您在学习过程中也遇到过一些常用的jQuery代码,欢迎分享.下边就让我们看看这些有代码片段. 1.jQuery得到用户IP: 复制代码 代码如下: $.getJSON("http://jsonip.appspot.com?callback=?", function (data) { alert("Your ip: " + data.ip); }); 2.jQuery查看图片的宽度和高度: 复制代码 代码如下: var t

BootStrap实用代码片段之一_javascript技巧

如题,持续总结自己在使用BootStrap中遇到的问题,并记录解决方法,希望能帮到需要的小伙伴. 应用场景:经典上下布局中,顶部导航条固定,下部填充不显示滚动条 解决方案:导航条固定在顶部,同时为body设置内边距(padding-top),内边距为导航条高度(默认50px,可自己调整高度),html代码如下: <!--html页面布局--> <div class="container-fluid page-wrapper"> <!--导航栏-->

jquery实用代码片段集合_jquery

加载google的jquery库 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script> 有利于加快加载速度(已经得到验证). 修改图片src更新图片 $(imageobj).attr('src', $(imageobj).attr('src') + '?' + Math.ra

整理几个常用的Python功能代码片段【收藏】

随机数生成 >>> import random  #导入Python内置的随机模块 >>> num = random.randint(1,1000)  #生成1-1000之间的伪随机数 读文件 >>> f = open("c:1.txt","r") >>> lines = f.readlines() #读出所有内容给变量 f >>> for line in lines: # 用

C#程序员经常用到的10个实用代码片段

1 读取操作系统和CLR的版本 OperatingSystem os = System.Environment.OSVersion;  Console.WriteLine("Platform: {0}", os.Platform);  Console.WriteLine("Service Pack: {0}", os.ServicePack);  Console.WriteLine("Version: {0}", os.Version);  Co