Jul-14-2019, 01:02 PM
It's a way to create functions out of class instances.
In the expression
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 operatorThe __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
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures