Examples of __call__ usages in Python _python

Source: Internet
Author: User

This example describes the use of __call__ in Python and shares it for your reference. The specific methods are as follows:

Let's take a look at the following sample code:

#call. py A class is loaded in the case.
class Next:
  List = []
  
  def __init__ (Self,low,high): for
    Num in range (Low,high):
      self. List.append (Num * * 2)
  
  def __call__ (self,nu): Return
    self. LIST[NU]

If you use this:

b = Next (1,7)
print b.list
print B (2)

Then feedback is normal:

[1, 4, 9, +]
9

But if you use this:

b = Next
B (1,7)
print b.list
print B (2)
$python./call.py
[1, 4, 9,,,]

traceback ( Most recent called last):
 File "cal.py", line <module>
  print B (2) 
TypeError: __init__ () takes ex actly 3 Arguments (2 given)

__INIT__ is an initialization function that is executed when an instance of the class is generated.

And __call__ is an impersonation () call that needs to be applied on an instance, so this instance is naturally already executed __init__.

The following example that you have raised:

b = Next

This is not to create an instance, but to assign the class to a variable. So the next operation with B is the operation of the following class, which is actually:

Next (1,7)
print next.list
print next (2)

I hope this article will help you with your Python programming.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.