python进阶五(定制类)【5-8 python中__call__】

python中 __call__

在Python中,函数其实是一个对象:

1 >>> f = abs
2 >>> f.__name__
3 'abs'
4 >>> f(-123)
5 123

由于 f 可以被调用,所以,f 被称为可调用对象。

所有的函数都是可调用对象。

一个类实例也可以变成一个可调用对象,只需要实现一个特殊方法__call__()

我们把 Person 类变成一个可调用对象:

1 class Person(object):
2     def __init__(self, name, gender):
3         self.name = name
4         self.gender = gender
5 
6     def __call__(self, friend):
7         print 'My name is %s...' % self.name
8         print 'My friend is %s...' % friend

现在可以对 Person 实例直接调用:

1 >>> p = Person('Bob', 'male')
2 >>> p('Tim')
3 My name is Bob...
4 My friend is Tim...

任务

改进一下前面定义的斐波那契数列:

class Fib(object):
    ???

请加一个__call__方法,让调用更简单:

1 >>> f = Fib()
2 >>> print f(10)
3 [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
 1 class Fib(object):
 2     def __call__(self, num):
 3         a, b, L = 0, 1, []
 4         for n in range(num):
 5             L.append(a)
 6             a, b = b, a + b
 7         return L
 8 
 9 f = Fib()
10 print f(10)

 

posted on 2019-10-06 13:18  ucas_python  阅读(228)  评论(0编辑  收藏  举报