Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"self" in python lambda expression

Tags:

python

lambda

def buildTestCase(xmlfile, description, method, evalString):
  func = lambda self, xmlfile=xmlfile, method=method, evalString=evalString: \
       method(self, evalString, feedparser.parse(xmlfile))  
  func.__doc__ = description
  return func

Above is a code snippet from feedparser, why there is a "self" in function definition method(self, evalString, feedparser.parse(xmlfile))?

Thanks.

like image 828
Fred HE Avatar asked Nov 15 '11 07:11

Fred HE


People also ask

What is lambda self in Python?

lambda returns a function. self is its argument, and i and j are enclosed inside of it. So, ch(i, j) is a function of i and j which returns a function of self. self does not have any magical meaning here as nothing in Python - every variable and function are explicit except of some built-ins.

What is self in Python function?

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

Is self mandatory in Python?

self is always required when referring to the instance itself, except when calling the base class constructor (wx. Frame. __init__). All the other variables that you see in the examples (panel, basicLabel, basicText, ...) are just local variables - not related to the current object at all.

Can lambda return 2 values Python?

Unlike a normal function, a lambda function contains only a single expression. Although, you can spread the expression over multiple lines using parentheses or a multiline string, but it should only remain as a single expression.


1 Answers

selfsimply refers to the first argument of the lambda named self.

the name self is not a reserved keyword, it is merely a convention above pythonistas to name the instance of the object on which the function applies. here, the author uses the name self as the first argument to the lambda, because this argument will receive an instance of an object on which the lambda will apply the method specified in the argument named method.

like image 63
Adrien Plisson Avatar answered Nov 14 '22 23:11

Adrien Plisson