Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Function object
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
== In Python == In [[Python (programming language)|Python]], functions are first-class objects, just like strings, numbers, lists etc. This feature eliminates the need to write a function object in many cases. Any object with a <code>__call__()</code> method can be called using function-call syntax. An example is this accumulator class (based on [[Paul Graham (computer programmer)|Paul Graham's]] study on programming language syntax and clarity):<ref>[http://www.paulgraham.com/accgen.html Accumulator Generator]</ref> <syntaxhighlight lang="python"> class Accumulator: def __init__(self, n) -> None: self.n = n def __call__(self, x): self.n += x return self.n </syntaxhighlight> An example of this in use (using the interactive interpreter): <syntaxhighlight lang="pycon"> >>> a = Accumulator(4) >>> a(5) 9 >>> a(2) 11 >>> b = Accumulator(42) >>> b(7) 49 </syntaxhighlight> Since functions are objects, they can also be defined locally, given attributes, and returned by other functions,<ref>[https://docs.python.org/3/reference/compound_stmts.html#function-definitions Python reference manual - Function definitions]</ref> as demonstrated in the following example: <syntaxhighlight lang="python3"> def Accumulator(n): def inc(x): nonlocal n n += x return n return inc </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)