Python Forum
What is the use of call method and when to use it?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
What is the use of call method and when to use it?
#2
It's a way to create functions out of class instances.

In the expression bar = foo(), the parentheses are an operator. Specifically, they are the function call operator. Normally you only see this with functions:

def foo(x):
    return 2 * x + 1
bar = foo(5)
#        ^ function call operator
The __call__ method of a class allows you to override that operator, just as the __add__ method allows you to override the + operator. This allows your class to operate as if it were a function. A typical example is to make an efficient factorial function by storing previously calculated values:

class Factorial(object):

    def __init__(self):
        self.facts = [1, 1]

    def __call__(self, x):
        try:
            return self.facts[x]
        except IndexError:
            while len(self.facts) <= x:
                self.facts.append(self.facts[-1] * len(self.facts))
            return self.facts[-1]
You can now create an instance of the factorial object and use it as a function:

Output:
>>> factorial = Factorial() >>> factorial(5) # adds items to factorial.facts 120 >>> factorial(3) # Use factorial.facts[3] 6
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Messages In This Thread
RE: What is the use of call method and when to use it? - by ichabod801 - Jul-14-2019, 01:02 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  method call help sollarriiii 6 1,155 Feb-21-2023, 03:19 AM
Last Post: noisefloor
  how to get around recursive method call Skaperen 10 4,291 Jul-01-2020, 10:09 PM
Last Post: Skaperen
  How to call COM-method using comtypes jespersahner 0 2,425 Nov-15-2019, 12:54 PM
Last Post: jespersahner
  Polymorphism not working with a call to a abstract method colt 3 2,337 Nov-04-2019, 11:04 PM
Last Post: colt
  How to Call a method of class having no argument dataplumber 7 6,454 Oct-31-2019, 01:52 PM
Last Post: dataplumber
  Call method from another method within a class anteboy65 3 7,466 Sep-11-2019, 08:40 PM
Last Post: Larz60+
  I'm trying to figure out whether this is a method or function call 357mag 2 2,430 Jul-04-2019, 01:43 AM
Last Post: ichabod801
  How to call a method in a module using code KingPieter 4 3,013 Jan-15-2019, 09:13 PM
Last Post: KingPieter
  call method in class using threads? masterofamn 0 2,709 Jan-24-2017, 09:09 PM
Last Post: masterofamn

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020