具有类似lisp的泛型函数的包。
gf的Python项目详细描述
概述
gf允许您编写泛型函数 generic functions 有了多个方法,就可以分派所有的参数。
简单示例
>>> from gf import generic, method >>> add = generic() >>> type(add) <type 'function'>
让我们为两个整数定义add:
>>> @method(int, int) ... def add(n0, n1): ... return n0 + n1
让我们测试一下:
>>> add(1, 2) 3
使用其他类型的实例调用add失败:
>>> add("Hello ", "World") Traceback (most recent call last): ... NotImplementedError: Generic '__main__.add' has no implementation for type(s): __builtin__.str, __builtin__.str
当然,add也可以定义为两个字符串:
>>> @method(basestring, basestring) ... def add(s0, s1): ... return s0 + s1
现在我们的hello world示例可以工作了:
>>> add("Hello ", "World") 'Hello World'
add也可以为字符串和整数定义:
>>> @method(basestring, int) ... def add(s, n): ... return s + str(n)
因此,我们可以添加一个字符串和一个数字:
>>> add("You ", 2) 'You 2'
python的特殊方法
gf.object将(几乎)所有special instance methods of a python object作为泛型函数实现。 该包包括一个rational number实现,它使 大量使用此功能:
@method(object,Rational)def__add__(a,b):"""Add an object and a rational number. `a` is converted to a `Rational` and then both are added."""returnRational(a)+b@method(Rational,object)def__add__(a,b):"""Add a rational number and an object. `b` is converted to a `Rational` and then both are added."""returna+Rational(b)
gf.object还有一种更简单的覆盖方法
对象。
@method(Rational,Writer)def__out__(rational,writer):"""Write a nice representation of the rational. Denominators that equal 1 are not printed."""writer("%d",rational.numerator)ifrational.denominator!=1:writer(" / %d",rational.denominator)@method(Rational,Writer)def__spy__(rational,writer):"""Write a debug representation of the rational."""writer("%s(",rational.__class__.__name__)ifrational.numerator!=0:writer("%r",rational.numerator)ifrational.denominator!=1:writer(", %r",rational.denominator)writer(")")
变化
每个版本中所做更改的简短草图。
释放0.1.4
以下内容已在0.1.4版中修复:
- Fixed an issue with variadic methods. Sometimes definitions of variadic methods added after the method was already called where not added.
- Specified and implemented a precedence rule for overlapping variadic methods of generic functions.
- Improved generated documentation for variadic methods.
- Fixed the markup of some notes in the documentation.
版本0.1.3
以下内容在0.1.3版中已更改:
- Added variadic methods, e.g. multi-methods with a variable number of arguments.
- Improved the long description text a bit and fixed bug in its markup.
- Fixed invalid references in the long description.
版本0.1.2
在0.1.2版中更改了以下内容:
- Added a generic functions for gf.Object.__call__.
- Added a gf.go.FinalizingMixin.
- gf.generic now also accepts a type.
- Improved the exception information for ambiguous calls.
- Fixed some documentation glitches.
发布0.1.1
这是最初的版本。
致谢
guido van rossum创建了这个包的核心。我刚把一些东西改名了 加了些方便的东西。谢谢你圭多!
版权所有
?2006 Python软件基金会。 2006-2013杰拉尔德·克利克斯版权所有。