python advanced five (custom class) [5-8 python in __call__]

python in __call__

In Python, an object is in fact a function of:

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

Since f can be called so, f is called callable object.

All functions are callable objects.

A class instance can become a callable object only needs to implement a particular method __ the __call () .

We become a Person class callable:

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

You can now direct calls to the Person instance:

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

task

Improved look at that number Fibonacci deed previously defined columns:

class Fib(object):
    ???

Please add a __call__ way to make calls more simply:

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)

 

Guess you like

Origin www.cnblogs.com/ucasljq/p/11627071.html