Function definition: Difference between revisions
Content added Content deleted
(→{{header|Perl 6}}: show lambdas too) |
(→{{header|Python}}: Consistency & simplification mods.) |
||
Line 857: | Line 857: | ||
=={{header|Python}}== |
=={{header|Python}}== |
||
Function definition: |
|||
Named function: |
|||
<lang python>def multiply(a, b): |
<lang python>def multiply(a, b): |
||
return a * b</lang> |
return a * b</lang> |
||
Lambda function definition: |
|||
<lang python>multiply = lambda a, b: a * b</lang> |
<lang python>multiply = lambda a, b: a * b</lang> |
||
A callable class |
A callable class definition allows functions and classes to use the same interface: |
||
<lang python>class |
<lang python>class Multiply: |
||
def __init__(self): |
|||
callcount = 0 |
|||
pass |
|||
self.multiplicand = a |
|||
def __call__(self, a, b): |
def __call__(self, a, b): |
||
return a * b |
|||
return self.multiplicand * a |
|||
m4 = Multiplier(4) |
|||
m2 = Multiplier(2) |
|||
print m4(2), m4(4), m4(12), m2(2), m2(3) |
|||
### >>> 4 8 48 4 6</lang> |
|||
multiply = Multiply() |
|||
(This trite example implements a simplistic "curried" multiplication class ... but also keeps track of the total number of times any instance has been called as a function. I can conceive of no useful application for it). |
|||
print multiply(2, 4) # prints 8</lang> |
|||
(No extra functionality is shown in ''this'' class definition). |
|||
=={{header|Q}}== |
=={{header|Q}}== |