I know that we can define class functions like so :
pp = lambda self,v: self.list[v]
but I am struggling with the syntax for defining the constructor the same way :
__init__ = lambda self: self.list = []
I googled around why this is not working but seems like nobody was crazy enough to try this. Folks who are knowledgeable in python internals, could you please help me understand why this is not working?
For people asking why do I want to do it this way - Just for the fun of coding and more knowledge, it would feel pretty amazing if it can be done somehow.
Axe answered it beautifully and I used it to solve a leetcode question - https://leetcode.com/problems/min-stack/discuss/2474150/BRUTALLY-OPTMISED-Python-Solution
CodePudding user response:
Disclaimer: This should not be done in production code unless you want your coworkers to hate you.
A lambda
is just a single line function with only an implicit return
statement.
So your first example pp = lambda self,v: self.list[v]
could be rewritten as:
def pp(self,v):
return self.list[v]
Doing so for your second example, __init__ = lambda self: self.list = []
would result in this:
def __init__(self):
return self.list = []
This isn't valid python syntax as self.list = []
isn't an expression and holds no value in itself.
You could use setattr()
which DOES return
something, None
.
__init__ = lambda self: setattr(self, 'list', [])
Rewritten as an actual method:
def __init__(self):
return setattr(self, 'list', [])