现在的位置: 首页 > 综合 > 正文

__call__

2012年09月01日 ⁄ 综合 ⁄ 共 664字 ⁄ 字号 评论关闭

一、

http://hi.baidu.com/feng2211/item/d55d0415602bfcfcdceeca45

Python中有一个有趣的语法,只要定义类型的时候,实现__call__函数,这个类型就成为可调用的。
换句话说,我们可以把这个类型的对象当作函数来使用,相当于 重载了括号运算符。
下面定义这样一个类型:
class g_dpm(object):
def __init__(self, g):
self.g = g
def __call__(self, t):
return (self.g*t**2)/2
计算地球场景的时候,我们就可以令e_dpm = g_dpm(9.8),s = e_dpm(t)。同样的方式,可以很容易的生成其他重力环境下的 自由落地公式。

二、

http://stackoverflow.com/questions/9663562/what-is-difference-between-init-and-call-in-python

The first is used to initialise newly created object, and receives arguments used to do that:

class foo:
    def __init__(self, a, b, c):
        # ...
x = foo(1, 2, 3) # __init__
The second implements function call operator.

class foo:
    def __call__(self, a, b, c):
        # ...
x = foo()
x(1, 2, 3) # __call__

抱歉!评论已关闭.