Python special function __call__ ()

Source: Internet
Author: User

__call__ in Python, the function is actually an object:>>> f = abs>>> f.__name__ ' abs ' >>> f (-123) 123 because F can be called, so, F is called a callable object. All functions are callable objects. An instance of a class can also become a callable object, just to implement 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 now On the person instance that can be called directly:>>> p = person (' bob ', ' Male ') >>> p (' Tim ') My name is Bob ... My Friend is Tim ... See P (' Tim ') you can't tell if P is a function or a class instance, so in Python, the function is also an object, and the difference between objects and functions is not significant. Task to improve the previously defined Fibonacci sequence: Class Fib (object):    ??? Please add a __call__ method to make the call simpler:>>> F = Fib () >>> print F (10) [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

The instance object can be represented in the form of a similar function, further blurring the concept between the function and the 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)

Python special function __call__ ()

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.