Fred HE
Fred HE

Reputation: 51

"self" in python lambda expression

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.

Upvotes: 5

Views: 11096

Answers (3)

Paul Manta
Paul Manta

Reputation: 31597

That lambda is intended to be used similarly to a class method. The self is the instance of the class, pretty much the same as the self in any other method.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

Methods can be called via their class by passing an instance of the class as the first argument. Since the first argument of a normal method is called self by convention, it is retained here.

>>> class C(object):
...   def foo(self):
...     print 42
... 
>>> c = C()
>>> C.foo(c)
42

Upvotes: 3

Adrien Plisson
Adrien Plisson

Reputation: 23303

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.

Upvotes: 7

Related Questions