__init__ as a lambda

Stefan Schwarzer sschwarzer at sschwarzer.net
Thu Aug 5 00:36:46 CEST 2010


Hi Eric,

On 2010-08-04 21:58, Eric J. Van der Velden wrote:
> class C:
>  def __init__(self,name):self.name=name
> 
> I was wondering if I could make the __init__ a lambda function, but
> 
> class C:
>  __init__=lambda self,self.name:None
> 
> and then later,
> 
> C('Hello')
> 
> does not work; the first argument, self, is assigned all rigth, but
> you cannot write the second argument with a dot,  self.name .

The "problem" is that in a lambda function the part after
the colon has to be an expression. However, you have used
an assignment there which isn't an expression in Python but
a statement.

For example, you can use

f = lambda x: sys.stdout.write(str(x))

(sys.stdout.write(str(x)) is an expression)

but not

f = lambda x: print x

(print x  is a statement in Python versions < 3)

Stefan



More information about the Python-list mailing list