Анонимные функции в JavaScript
Анонимной в JavaScript называют функцию с которой не связано никакое имя или другими словами у такой функции нет имени. Также можно сказать, что если после ключевого слова function или перед знаком стрелочной функции => не стоит имя — функция анонимная. Однако если такую функцию положить в переменную она уже считается именованной.
Анонимная функция недоступна после первоначального создания, поэтому чаще всего она записывается в переменную и дальше с ней происходит работа. Но есть случаи, когда функция так и остается без уникального идентификатора.
Самовызывающаяся функция
(function() < alert('Я буду настойчив и выучу все возможные записи функций!'); >)();
Такая анонимная функция выполнится сразу же, как интерпретатор до неё дойдет. В такой записи, функция заключается в круглые скобки () , а после нее добавляется вызов () .
Также запись может быть сделана в стиле стрелочных функций.
Анонимные функции в качестве параметров
Зачем присваивать функции имя, если ее вызов происходит здесь, сейчас и больше нигде.
setTimeout(function() < alert('Время заняться практикой JavaScript!'); >, 5000);
В данном примере анонимная функция выступает в качестве аргумента функции setTimeout() , и выведет сообщение через пять секунд после загрузки страницы.
Еще один пример, но уже не с кастомной функцией.
function importantQuestion(question, yes, no) < if (confirm(question)) yes() else no(); >importantQuestion( "Вы хотите изучать JavaScript?", function() < alert("Не опускайте руки и у вас все получиться!"); >, function() < alert("Отличная новость! Чем меньше у меня конкурентов, тем выше моя зарплата."); >);
Итого
1. Анонимные функции становятся доступны, только после того, как интерпретатор дойдет до них, таким образом их вызов возможен только после записи функции в коде.
2. Анонимные функции короче и отлично подходят в тех случаях, когда на них не нужно ссылаться в коде.
3. Анонимные функции могут вызывать сами себя.
4. Анонимные функции могут выступать в качестве параметров в других функциях.
Skypro — научим с нуля
PYTHON КАКОЕ СЛОВО ЗАРЕЗЕРВИРОВАНО ДЛЯ ОБОЗНАЧЕНИЯ АНОНИМНОЙ ФУНКЦИИ
В Python для обозначения анонимной функции используется ключевое слово lambda . Оно позволяет создавать функцию в одной строке кода без необходимости давать ей имя.
Пример создания анонимной функции с использованием lambda :
(lambda x: x + 10)(5)
(lambda a, b, c: a * b * c)(2, 3, 4)
В первом примере создаётся функция, которая прибавляет к своему аргументу 10, а затем вызывается с аргументом 5. Результат вычислений будет равен 15.
Во втором примере создаётся функция, которая умножает три своих аргумента, а затем она вызывается с аргументами 2, 3 и 4. Результат вычислений будет равен 24.
Lambda Python на русском за 5 минут — лямбда выражения Python
Python с нуля — Функции в Python — Определение, вызов, позиционные и именованные аргументы, return
37 Возвращаемое значение функции. Оператор return Python
35 Функции (def) в Python. Определение и вызов функции
Python с нуля. Урок 14 — Lambda-функции
#42. Анонимные (lambda) функции — Python для начинающих
45 Lambda функция Python. Lambda выражение. Анонимная функция Lambda

BLGPG-E72141397F38-23-11-23-13
Новые материалы:
- Объединить pdf python
- Автоматизация андроид приложений python
- Авторизация пользователя flask
- Админ панель django
- Имя переменной не может начинаться с цифры python
- Число капрекара в произвольной системе счисления python
- Pyautogui python скачать
- Python список квадратов
- Как найти отрицательные числа в массиве python
- Интерактивная подсказка python
- Очередь с приоритетом python
- Python вызов класса из функции
- Mac os установка python
- Напишите программу которая находит максимальный и минимальный из элементов массива с четными python
Какое слово зарезервировано для обозначения анонимной функции
Watch out when ‘importing’ variables to a closure’s scope — it’s easy to miss / forget that they are actually being *copied* into the closure’s scope, rather than just being made available.
So you will need to explicitly pass them in by reference if your closure cares about their contents over time:
$one (); // outputs NULL: $result is not in scope
$two (); // outputs int(0): $result was copied
$three (); // outputs int(1)
?>
Another less trivial example with objects (what I actually tripped up on):
//set up variable in advance
$myInstance = null ;
$broken = function() uses ( $myInstance )
if(!empty( $myInstance )) $myInstance -> doSomething ();
>;
//$myInstance might be instantiated, might not be
if( SomeBusinessLogic :: worked () == true )
$myInstance = new myClass ();
>
$broken (); // will never do anything: $myInstance will ALWAYS be null inside this closure.
$working (); // will call doSomething if $myInstance is instantiated
8 years ago
/*
(string) $name Name of the function that you will add to class.
Usage : $Foo->add(function()<>,$name);
This will add a public function in Foo Class.
*/
class Foo
public function add ( $func , $name )
$this -> < $name >= $func ;
>
public function __call ( $func , $arguments ) call_user_func_array ( $this ->< $func >, $arguments );
>
>
$Foo = new Foo ();
$Foo -> add (function() echo «Hello World» ;
>, «helloWorldFunction» );
$Foo -> add (function( $parameterone ) echo $parameterone ;
>, «exampleFunction» );
$Foo -> helloWorldFunction (); /*Output : Hello World*/
$Foo -> exampleFunction ( «Hello PHP» ); /*Output : Hello PHP*/
?>?php
9 years ago
In case you were wondering (cause i was), anonymous functions can return references just like named functions can. Simply use the & the same way you would for a named function. right after the `function` keyword (and right before the nonexistent name).
$x =& $fn ();
var_dump ( $x , $value ); // ‘int(0)’, ‘int(0)’
++ $x ;
var_dump ( $x , $value ); // ‘int(1)’, ‘int(1)’
5 years ago
Every instance of a lambda has own instance of static variables. This provides for great event handlers, accumulators, etc., etc.
Creating new lambda with function() < . >; expression creates new instance of its static variables. Assigning a lambda to a variable does not create a new instance. A lambda is object of class Closure, and assigning lambdas to variables has the same semantics as assigning object instance to variables.
Example script: $a and $b have separate instances of static variables, thus produce different output. However $b and $c share their instance of static variables — because $c is refers to the same object of class Closure as $b — thus produce the same output.
function generate_lambda () : Closure
# creates new instance of lambda
return function( $v = null ) static $stored ;
if ( $v !== null )
$stored = $v ;
return $stored ;
>;
>
$a = generate_lambda (); # creates new instance of statics
$b = generate_lambda (); # creates new instance of statics
$c = $b ; # uses the same instance of statics as $b
$a ( ‘test AAA’ );
$b ( ‘test BBB’ );
$c ( ‘test CCC’ ); # this overwrites content held by $b, because it refers to the same object
var_dump ([ $a (), $b (), $c () ]);
?>
This test script outputs:
array(3) [0]=>
string(8) «test AAA»
[1]=>
string(8) «test CCC»
[2]=>
string(8) «test CCC»
>
6 years ago
One way to call a anonymous function recursively is to use the USE keyword and pass a reference to the function itself:
14 years ago
When using anonymous functions as properties in Classes, note that there are three name scopes: one for constants, one for properties and one for methods. That means, you can use the same name for a constant, for a property and for a method at a time.
Since a property can be also an anonymous function as of PHP 5.3.0, an oddity arises when they share the same name, not meaning that there would be any conflict.
Consider the following example:
class MyClass const member = 1 ;
public function member () return «method ‘member'» ;
>
public function __construct () $this -> member = function () return «anonymous function ‘member'» ;
>;
>
>
header ( «Content-Type: text/plain» );
$myObj = new MyClass ();
var_dump ( MyClass :: member ); // int(1)
var_dump ( $myObj -> member ); // object(Closure)#2 (0) <>
var_dump ( $myObj -> member ()); // string(15) «method ‘member'»
$myMember = $myObj -> member ;
var_dump ( $myMember ()); // string(27) «anonymous function ‘member'»
?>
That means, regular method invocations work like expected and like before. The anonymous function instead, must be retrieved into a variable first (just like a property) and can only then be invoked.
12 years ago
/*
* An example showing how to use closures to implement a Python-like decorator
* pattern.
*
* My goal was that you should be able to decorate a function with any
* other function, then call the decorated function directly:
*
* Define function: $foo = function($a, $b, $c, . ) <. >
* Define decorator: $decorator = function($func) <. >
* Decorate it: $foo = $decorator($foo)
* Call it: $foo($a, $b, $c, . )
*
* This example show an authentication decorator for a service, using a simple
* mock session and mock service.
*/
/*
* Define an example decorator. A decorator function should take the form:
* $decorator = function($func) * return function() use $func) * // Do something, then call the decorated function when needed:
* $args = func_get_args($func);
* call_user_func_array($func, $args);
* // Do something else.
* >;
* >;
*/
$authorise = function( $func ) return function() use ( $func ) if ( $_SESSION [ ‘is_authorised’ ] == true ) $args = func_get_args ( $func );
call_user_func_array ( $func , $args );
>
else echo «Access Denied» ;
>
>;
>;
/*
* Define a function to be decorated, in this example a mock service that
* need to be authorised.
*/
$service = function( $foo ) echo «Service returns: $foo » ;
>;
/*
* Decorate it. Ensure you replace the origin function reference with the
* decorated function; ie just $authorise($service) won’t work, so do
* $service = $authorise($service)
*/
$service = $authorise ( $service );
/*
* Establish mock authorisation, call the service; should get
* ‘Service returns: test 1’.
*/
$_SESSION [ ‘is_authorised’ ] = true ;
$service ( ‘test 1’ );
/*
* Remove mock authorisation, call the service; should get ‘Access Denied’.
*/
$_SESSION [ ‘is_authorised’ ] = false ;
$service ( ‘test 2’ );
4 years ago
Beware of using $this in anonymous functions assigned to a static variable.
class Foo public function bar () static $anonymous = null ;
if ( $anonymous === null ) // Expression is not allowed as static initializer workaround
$anonymous = function () return $this ;
>;
>
return $anonymous ();
>
>
$a = new Foo ();
$b = new Foo ();
var_dump ( $a -> bar () === $a ); // True
var_dump ( $b -> bar () === $a ); // Also true
?>
In a static anonymous function, $this will be the value of whatever object instance that method was called on first.
To get the behaviour you’re probably expecting, you need to pass the $this context into the function.
class Foo public function bar () static $anonymous = null ;
if ( $anonymous === null ) // Expression is not allowed as static initializer workaround
$anonymous = function ( self $thisObj ) return $thisObj ;
>;
>
return $anonymous ( $this );
>
>
$a = new Foo ();
$b = new Foo ();
var_dump ( $a -> bar () === $a ); // True
var_dump ( $b -> bar () === $a ); // False
?>
9 years ago
Beware that since PHP 5.4 registering a Closure as an object property that has been instantiated in the same object scope will create a circular reference which prevents immediate object destruction:
class Test
private $closure ;
public function __construct ()
$this -> closure = function () >;
>
public function __destruct ()
echo «destructed\n» ;
>
>
new Test ;
echo «finished\n» ;
?>
To circumvent this, you can instantiate the Closure in a static method:
public function __construct ()
$this -> closure = self :: createClosure ();
>
public static function createClosure ()
return function () >;
>
6 years ago
PERFORMANCE BENCHMARK 2017!
I decided to compare a single, saved closure against constantly creating the same anonymous closure on every loop iteration. And I tried 10 million loop iterations, in PHP 7.0.14 from Dec 2016. Result:
a single saved closure kept in a variable and re-used (10000000 iterations): 1.3874590396881 seconds
new anonymous closure created each time (10000000 iterations): 2.8460240364075 seconds
In other words, over the course of 10 million iterations, creating the closure again during every iteration only added a total of «1.459 seconds» to the runtime. So that means that every creation of a new anonymous closure takes about 146 nanoseconds on my 7 years old dual-core laptop. I guess PHP keeps a cached «template» for the anonymous function and therefore doesn’t need much time to create a new instance of the closure!
So you do NOT have to worry about constantly re-creating your anonymous closures over and over again in tight loops! At least not as of PHP 7! There is absolutely NO need to save an instance in a variable and re-use it. And not being restricted by that is a great thing, because it means you can feel free to use anonymous functions exactly where they matter, as opposed to defining them somewhere else in the code. 🙂
9 years ago
Some comparisons of PHP and JavaScript closures.
=== Example 1 (passing by value) ===
PHP code:
$aaa = 111 ;
$func = function() use( $aaa )< print $aaa ; >;
$aaa = 222 ;
$func (); // Outputs «111»
?>
Similar JavaScript code:
Be careful, following code is not similar to previous code:
var aaa = 111;
var bbb = aaa;
var func = function()< alert(bbb); >;
aaa = 222;
func(); // Outputs «111», but only while «bbb» is not changed after function declaration
// And this technique is not working in loops:
var functions = [];
for (var i = 0; i < 2; i++)
var i2 = i;
functions.push(function()< alert(i2); >);
>
functions[0](); // Outputs «1», wrong!
functions[1](); // Outputs «1», ok
=== Example 2 (passing by reference) ===
PHP code:
$aaa = 111 ;
$func = function() use(& $aaa )< print $aaa ; >;
$aaa = 222 ;
$func (); // Outputs «222»
?>
Similar JavaScript code:
13 years ago
You can always call protected members using the __call() method — similar to how you hack around this in Ruby using send.
class Fun
<
protected function debug ( $message )
<
echo «DEBUG: $message \n» ;
>
public function yield_something ( $callback )
<
return $callback ( «Soemthing!!» );
>
public function having_fun ()
<
$self =& $this ;
return $this -> yield_something (function( $data ) use (& $self )
<
$self -> debug ( «Doing stuff to the data» );
// do something with $data
$self -> debug ( «Finished doing stuff with the data.» );
>);
>
// Ah-Ha!
public function __call ( $method , $args = array())
<
if( is_callable (array( $this , $method )))
return call_user_func_array (array( $this , $method ), $args );
>
>
$fun = new Fun ();
echo $fun -> having_fun ();
5 years ago
As of PHP 7.0, you can use IIFE(Immediately-invoked function expression) by wrapping your anonymous function with ().
$type = ‘number’ ;
var_dump ( . ( function() use ( $type ) <
if ( $type == ‘number’ ) return [ 1 , 2 , 3 ];
else if ( $type == ‘alphabet’ ) return [ ‘a’ , ‘b’ , ‘c’ ];
> )() );
?>
13 years ago
Here is an example of one way to define, then use the variable ( $this ) in Closure functions. The code below explores all uses, and shows restrictions.
The most useful tool in this snippet is the requesting_class() function that will tell you which class is responsible for executing the current Closure().
Overview:
————————
Successfully find calling object reference.
Successfully call $this(__invoke);
Successfully reference $$this->name;
Successfully call call_user_func(array($this, ‘method’))
Failure: reference anything through $this->
Failure: $this->name = »;
Failure: $this->delfect();
function requesting_class ()
foreach( debug_backtrace ( true ) as $stack ) if(isset( $stack [ ‘object’ ])) return $stack [ ‘object’ ];
>
>
class Person
public $name = » ;
public $head = true ;
public $feet = true ;
public $deflected = false ;
function __invoke ( $p ) < return $this ->$p ; >
function __toString () < return 'this' ; >// test for reference
function __construct ( $name ) < $this ->name = $name ; >
function deflect () < $this ->deflected = true ; >
public function shoot ()
< // If customAttack is defined, use that as the shoot resut. Otherwise shoot feet
if( is_callable ( $this -> customAttack )) return call_user_func ( $this -> customAttack );
>
$p = new Person ( ‘Bob’ );
$p -> customAttack =
function()
echo $this ; // Notice: Undefined variable: this
#$this = new Class() // FATAL ERROR
// Trick to assign the variable ‘$this’
extract (array( ‘this’ => requesting_class ())); // Determine what class is responsible for making the call to Closure
var_dump ( $this ); // Passive reference works
var_dump ( $ $this ); // Added to class: function __toString()
$name = $this ( ‘name’ ); // Success
echo $name ; // Outputs: Bob
echo ‘
‘ ;
echo $ $this -> name ;
call_user_func_array (array( $this , ‘deflect’ ), array()); // SUCCESSFULLY CALLED
#$this->head = 0; //** FATAL ERROR: Using $this when not in object context
$ $this -> head = 0 ; // Successfully sets value
13 years ago
If you want to make a recursive closure, you will need to write this:
function($param1, $param2) use ($some_var1, $some_var2)
call_user_func(__FUNCTION__, $other_param1, $other_param2);
If you need to pass values by reference you should check out
If you’re wondering if $some_var1 and $some_var2 are still visible by using the call_user_func, yes, they are available.
11 years ago
Since it is possible to assign closures to class variables, it is a shame it is not possible to call them directly. ie. the following does not work:
class foo
public function __construct () $this -> test = function( $a ) print » $a \n» ;
>;
>
>
$f -> test ();
?>
However, it is possible using the magic __call function:
class foo
public function __construct () $this -> test = function( $a ) print » $a \n» ;
>;
>
public function __call ( $method , $args ) if ( $this -> < $method >instanceof Closure ) return call_user_func_array ( $this ->< $method >, $args );
> else return parent :: __call ( $method , $args );
>
>
>
$f = new foo ();
$f -> test ();
?>
it
Hope it helps someone 😉
14 years ago
If you want to check whether you’re dealing with a closure specifically and not a string or array callback you can do this:
1 month ago
«If this automatic binding of the current class is not wanted, then static anonymous functions may be used instead. «
The main reason why you would not want automatic binding is that as long as the Closure object created for the anonymous function exists, it retains a reference to the object that spawned it, preventing the object from being destroyed, even if the object is no longer alive anywhere else in the program, and even if the function itself doesn’t use $this.
class Foo
public function __construct (private string $id )
echo «Creating Foo » . $this -> id , «\n» ;
>
public function gimme_function ()
return function()<>;
>
public function gimme_static_function ()
return static function()<>;
>
public function __destruct ()
echo «Destroying Foo » . $this -> id , «\n» ;
>
>
echo «An object is destroyed as soon as its last reference is removed.\n» ;
$t = new Foo ( ‘Alice’ );
$t = new Foo ( ‘Bob’ ); // Causes Alice to be destroyed.
// Now destroy Bob.
unset( $t );
echo «—\n» ;
echo «A non-static anonymous function retains a reference to the object which created it.\n» ;
$u = new Foo ( ‘Carol’ );
$ufn = $u -> gimme_function ();
$u = new Foo ( ‘Daisy’ ); // Does not cause Carol to be destroyed,
// because there is still a reference to
// it in the function held by $ufn.
unset( $u ); // Causes Daisy to be destroyed.
echo «—\n» ; // Note that Carol hasn’t been destroyed yet.
echo «A static anonymous function does not retain a reference to the object which created it.\n» ;
$v = new Foo ( ‘Eve’ );
$vfn = $v -> gimme_static_function ();
$v = new Foo ( ‘Farid’ ); // The function held by $vfn does not
// hold a reference to Eve, so Eve does get destroyed here.
unset( $v ); // Destroy Farid
echo «—\n» ;
// And then the program finishes, discarding any references to any objects still alive
// (specifically, Carol).
?>
Because $ufn survived to the end of the end of the program, Carol survived as well. $vfn also survived to the end of the program, but the function it contained was declared static, so didn’t retain a reference to Eve.
Anonymous functions that retain references to otherwise-dead objects are therefore a potential source of memory leaks. If the function has no use for the object that spawned it, declaring it static prevents it from causing the object to outlive its usefulness.
- Функции
- Функции, определяемые пользователем
- Аргументы функции
- Возврат значений
- Обращение к функциям через переменные
- Встроенные функции
- Анонимные функции
- Стрелочные функции
- Callback-функции как объекты первого класса
- Copyright © 2001-2023 The PHP Group
- My PHP.net
- Contact
- Other PHP.net sites
- Privacy policy
Анонимные функции — Python: Функции
Представим, что нам нужно написать функцию для выполнения определенного действия, но создание отдельной функции кажется излишним. Чтобы решить эту проблему, можно использовать анонимные функции. Они позволяют определить функцию «на лету» внутри другой функции или выражения.
В этом уроке мы изучим, что такое анонимные функции, как их определять и использовать в Python. Также рассмотрим примеры, где использование анонимных функций может значительно упростить написание кода. Но для начала вспомним, что такое именованные функции.
Принцип работы именованных функций
Именованные функции в Python — это функции, которым назначено имя с помощью оператора def . Он позволяет создавать функции, которые можно вызывать по имени из любой точки программы.
Пример именованной функции:
def add_numbers(x, y): return x + yЗдесь именованная функция — add_numbers . Она принимает два аргумента x и y и возвращает их сумму.
Еще бывают ситуации, когда нужна функция, чтобы ее передать, например, в функцию высшего порядка. Но больше эта функция нигде не понадобится.
Придумывание имен в программировании — одна из основных проблем. Но если функция нужна здесь и сейчас, и больше нигде ее вызывать не придется, то и имя ей не нужно. Такие одноразовые функции называются анонимными или лямбда-функциями.
Принцип работы анонимных функций
Анонимные функции — это функции, у которых нет имени. Они определяются с помощью ключевого слова lambda . Это ключевое слово названо в честь лямбда-абстракции — основы Лямбда Исчисления. Это математический аппарат, который часто применяется в разработке языков программирования. В Лямбда Исчислении все функции — анонимные. Поэтому анонимные функции во многих языках тоже иногда называют лямбдами или лямбда-функциями.
Такие функции обычно используются в качестве аргументов функций высшего порядка, таких как map() , filter() и reduce() . Также они позволяют описывать практически все языки, которые умеют работать с функциями как со значениями.
В Python определение подобной функции выглядит так:
lambda x: x + 1 # at 0x7f56e5798a60>Мы сконструировали функцию, но имя она не получила, поэтому REPL ее отобразил как function .
Рассмотрим пример, который использует анонимную функцию:
l = [1, 2, 5, 3, 4] l.sort(key=lambda x: -x) l # [5, 4, 3, 2, 1]Метод sort принимает в качестве аргумента key ссылку на функцию. В примере в качестве аргумента указана функция, которая меняет знак у аргумента. По этой причине список получается отсортирован от большего к меньшему.
Сортировка с указанием ключа встречается довольно часто, а вот ключи сортировки чаще всего будут разными. Поэтому выносить ключи в именованные функции смысла нет и анонимные функции здесь подходят.
Рассмотрим другой пример, который использует анонимную функцию вместе с функцией map() :
l = [1, 2, 3, 4, 5] result = list(map(lambda x: x * 2, l)) result # [2, 4, 6, 8, 10]В данном примере функция map() принимает анонимную функцию и список данных. Анонимная функция lambda x: x * 2 принимает один аргумент x и умножает его на два. Функция map() применяет эту анонимную функцию к каждому элементу списка l и возвращает новый список, в котором каждый элемент удвоен. Результат сохраняется в переменной result и выводится на экран.
Теперь рассмотрим пример работы с функцией filter :
l = [1, 2, 3, 4, 5] result = list(filter(lambda x: x % 2 == 0, l)) result # [2, 4]Этот код использует функцию filter . Она фильтрует элементы входной последовательности, согласно условию, которое задано в лямбда-функции. В нашем примере функция фильтрует элементы списка l .
Здесь лямбда-функция lambda x: x % 2 == 0 определяет, что элемент должен быть четным — его остаток при делении на два должен быть равен нулю.
Функция filter применяет лямбда-функцию к каждому элементу списка l и оставляет только те элементы, для которых лямбда-функция возвращает True . Затем эти элементы используются для создания нового списка с помощью функции list .
Посмотрим на еще один пример применения анонимной функции, но уже с функцией reduce :
from functools import reduce l = [1, 2, 3, 4, 5] result = reduce(lambda x, y: x * y, l) result # 120В данном примере используется лямбда-функция, которая принимает два аргумента: x и y . В итоге она возвращает их произведение. Итерируемый объект l содержит числа [1, 2, 3, 4, 5] . Поэтому функция reduce последовательно умножает каждую пару чисел в списке: (1 * 2) * 3) * 4) * 5 . Это приводит к результату 120 .
Особенности анонимных функций
Рассмотрим главные особенности анонимных функций:
- Аргументы анонимных функций не заключены в скобки. К этому нужно будет привыкнуть. Остальные средства для описания аргументов доступны в полной мере — и именованные аргументы, и *args с **kwargs
- Тело лямбда-функции — это всегда одно выражение, результат вычисления которого и будет возвращаемым значением. В теле лямбда-функции не получится выполнить несколько действий и не получится использовать многострочные конструкции вроде for и while . Но зато анонимные функции обычно просто читать, чего было бы сложно добиться, разреши авторам «многострочные» лямбды
- Объявление функции является выражением. Функции можно конструировать и тут же вызывать, не заканчивая выражение:
1 + (lambda x: x * 5)(8) + 1 # 42В таком виде лямбды встречаются редко. Зато часто можно встретить возврат лямбды из функции:
def caller(arg): return lambda f: f(arg) call_with_five = caller(5) call_with_five(str) # '5' call_with_five(lambda x: x + 1) # 6Из этого примера можно понять, что лямбды являются замыканиями — возвращаемая лямбда запоминает значение переменной arg .
Открыть доступ
Курсы программирования для новичков и опытных разработчиков. Начните обучение бесплатно
- 130 курсов, 2000+ часов теории
- 1000 практических заданий в браузере
- 360 000 студентов
Наши выпускники работают в компаниях:
