2009-09-10 02:43:35
涉及的技术内容包括:ASM、C、.NET/C#、Python、Linux/Ubuntu 等。
记录读书笔记、生活点滴。关注基础理论和开发……
除特别标注外,所有文章均为作者原创,转载请注明出处。谢谢!

  查看 "推荐文章目录"。  


  雨痕内部技术交流群,欢迎熟识的朋友参与。 将 添加为您的 MSN 联系人即可。
  承接搜索引擎开发项目;寻求搜索引擎商业合作伙伴。
  为杜绝垃圾广告的侵扰,只有注册用户可以发表评论和留言。
  如果有什么问题,可以单击右侧图标给雨痕发消息。( 绿色: 在线; 灰色: 脱机)
浏览模式: 普通 | 列表

Python Library: Exec & Compile

[ 2010-03-10 10:31:00 | 作者: yuhen ]
直接运行代码字符串也是动态语言的一个重要特征。虽然在 .NET/C# 里也可通过 CodeDom 实现类似的功能,但远没 Python 这么方便自由。
>>> code = """
def test(s):
  print "test:", s

a = 123
"""
>>> exec code

>>> a
123

>>> test("abc")
test: abc

内置函数里还有 eval() 和 execfile() 都是用来做类似事情的。exec 关键字执行多行代码片段,eval() 函数通常用来执行一条包含返回值的表达式,而 execfile 自然是用来执行源码文件了。
>>> a = 10

>>> x = eval("a + 3")

>>> x
13

eval() 和 execfile() ...

阅读全文…

Python Library: Encoding

[ 2010-03-08 17:53:23 | 作者: yuhen ]
字符编码转换是个常用的内容。Python 标准库提供了一个 codecs Module,类似 .NET System.Text.Encoding。

C# 代码
var s = "中国人";
var encoding = Encoding.GetEncoding("gb2312");

var bytes = encoding.GetBytes(s);
      
Array.ForEach(bytes, b => Console.Write("{0:x} ", b));
Console.WriteLine();

var ds = encoding.GetString(bytes);
Console.WriteLine(ds);

输出:
d6 d0 b9 fa c8 cb
中国人

Python 代码
#!/usr/bin/env python
...

阅读全文…

Python Essential: 11. Metaclasses

[ 2010-03-08 14:16:56 | 作者: yuhen ]
Metaclass 允许我们在 Class Object 创建时插入扩展逻辑,且不需要对目标名进行重新绑定。Python 提供的几种扩展和拦截手段中,Descriptor 针对 Class.Attribute 进行拦截但却非扩展,用于 Class 内在行为的调度;Class Decorator 目标是 Instance Object,可以拦截对象创建和成员调用,但需要对目标名进行重绑定,所有一切都要透过包装进行;Metaclass 要对付的是 Class 本身,它掌控对象之源,搓圆捏扁随意为之。大杀器!不过麻烦也多。如果实在无聊,或者要整一些 NB 的概念,可以试试看。

举个简单的例子:假如我们希望对多个没有继承关系的类(class)添加某个通用方法,该怎么做?

方法1: 添加包含该方法的扩展基类,反正 Python 支持多重继承。
方法2: 利用 Class Decorator ...

阅读全文…

Python Essential: 10. Descriptors (2)

[ 2010-03-08 01:24:02 | 作者: yuhen ]
3. Open Class

Open Class 是脚本语言吸引人的一个重要特征,允许我们在运行时随时增删对象字段和方法。但在 Python 中,我们会发现向对象动态添加方法后,其调用方式和内置方法不尽相同。
>>> class MyClass(object):
  def __init__(self, x = 123):
    self.x = x
  def test(self, s):
    print s, self.x

    
>>> o = MyClass()

>>> o.test("abc")
abc 123

>>> def test2(self, s):
  print "test2:", s, self.x

  
>>> o.test2 = test2

>>> o.test2("abc") # 为啥一样的方法调用会失败呢?

Traceback (most recent call last):
...

阅读全文…

Python Essential: 10. Descriptors (1)

[ 2010-03-08 00:42:09 | 作者: yuhen ]
Descriptor 提供了另外一种拦截 Attribute 访问的方法。比如我们前面用 property(get, set, del) 定义属性的做法。Descriptor 可以分别拦截 Attribute 的 get, set ,del 操作,并用一个实现了所谓 Descriptor Protocol 的对象来完成相关操作。
class Descriptor(object):
  def __init__(self, name, value):
    self.name = name
    self.value = value
  def __get__(self, obj, objtype):
    print "get:", obj, self.name
    return self.value
  def __set__(self, obj, value):
...

阅读全文…

Python Essential: 9. Decorators (2)

[ 2010-03-07 18:59:20 | 作者: yuhen ]
3. Decorator Nesting

看下面的分解伪码,很容易理解。
@a
@b
def func(): ...

相当于:
def func(): ...
func = a(b(func))

写个例子测试一下:
def a(func):
  print "decorator a:", func

  def wa(*args):
    print "wa:", args
    func(*args)
  
  return wa

def b(func):
  print "decorator b:", func

  def wb(*args):
    print "wb:", args
    func(*args)

  return wb

 
@a
@b
def test(s): print "test:", s
...

阅读全文…

Python Essential: 9. Decorators (1)

[ 2010-03-07 17:43:12 | 作者: yuhen ]
Python Decorator 看上去有点像 C# Attribute,但 Decorator 是一种运行期 Hook,类似 AOP 而非添加 Metadata 数据。简单点说,Decorator 提供了一种方法在函数和类尾部插入自动运行代码,通过重新绑定目标名称为包装类型(Wrapper)来达到拦截目标调用的能力。
@decorator
def <name>(): ...code block...

被转换为:
def <name>(): ...code block...
<name> = decorator(name)

下次调用 <name>() 实际会调用 decorator.__call__,如此就实现了目标拦截操作。

1. Function Decorator

...

阅读全文…

Python Essential: 8. Exceptions

[ 2010-03-07 01:28:28 | 作者: yuhen ]
1. try/except/finally

Python 的异常处理机制和 C# 蛮像的。
# -*- coding: utf-8 -*-

class MyException(Exception):
  def __init__(self, message):
    Exception.__init__(self)
    self.message = message
 
def test(s):
  try:
    if type(s) is not str: raise MyException("error!")
    print s
  except Exception as e:
    print e.message
  else:
    print "noerror"
  finally:
    print "finally"

test(123)
...

阅读全文…