Example explanation of improving sequence in call in Python

  • 2021-08-21 20:49:22
  • OfStack

We've all had the experience of function calls, so call calls an instance of a class much like a function. Many people know the usage of classes. What are class instances? The class can be regarded as a design drawing, and the class instance is the finished product designed. Now that we have figured out the concept of call calling objects, we can take one step further to improve arrays in python. If you want to learn, look down.

__call__()

In Python, the functional first-class object, which means that a function can be passed to another function or method, can be returned from a subroutine, and can be assigned to a variable.

Instances of a class can also be treated like Function 1, such as passing them to other functions or methods and being called. To do this, define the __call__ () method specifically in the class.

def __call__ (self, [args...]) It accepts 1 series of parameters. Assuming that x is an instance of the class X, x.__call__ (1, 2) is equivalent to calling x (1, 2), and the instance x seems to be a function.

Fibonacci sequence under improvement 1:


class Fib(object):

Add a __call__ method to make the call easier:


>>> f = Fib()
>>> print(f(10))
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

The instance object can be expressed in the form of a function, which blurs the concept between function and object.


class Fib(object):
 def __init__(self):
  pass
 def __call__(self,num):
  a,b = 0,1;
  self.l=[]
  for i in range (num):
   self.l.append(a)
   a,b= b,a+b
  return self.l
 def __str__(self):
  return str(self.l)
 __rept__=__str__ 
f = Fib()
print(f(10))

__call__ () Knowledge Point Extension

In Python, a function is actually an object:


>>> f = abs
>>> f.__name__
'abs'
>>> f(-123)

Because f can be called, f is called a callable object.

All functions are callable objects.

A class instance can also become a callable object by implementing a special method __call__ ().

We turn the Person class into a callable object:


class Person(object):
def __init__(self, name, gender):
self.name = name
self.gender = gender
 
def __call__(self, friend):
print 'My name is %s...' % self.name
print 'My friend is %s...' % friend

You can now call directly on the Person instance:


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

Just looking at p ('Tim'), you can't tell whether p is a function or a class instance. Therefore, in Python, functions are also objects, and the difference between objects and functions is not significant.

Consideration and expansion of sub-knowledge points, this site will be in the follow-up and supplement, thank you for your support of this site.


Related articles: