[PYTHON] Let's write class __str__ more easily using lambda!

Hello of lambda fan you do not know have much in the Pythonista! Well, I think you are using __str__ or __unicode__ to display the name of the class. Specifically, I think we are making the following class declaration.

python



class NotLambda(object):

    name = u'not lambda'

    def __str__(self):
        return '<%s>' % self.name

But don't you think this declaration is a bit verbose? Especially def --return. Probably, in most cases, it is a declaration that only one line is enough.

So, by the way, lambda was convenient for such a declaration. Using lambda, you can write as below.

python


class UseLambda(object):

    name = u'lambda'
    __str__ = lambda self: '<%s>' % self.name

I think that lambda has the following behavior when converted to def.

python


def not_lambda(hoge):
    return hoge + 1

test_def = not_lambda
print test_def(1)

In other words, by creating a function and connecting it to that variable, you can use that variable as a function. If you change it to lambda, it will be below.

python


test_lambda = lambda hoge: hoge + 1
print test_lambda(1)

So, __str__ could be defined in lambda. To be honest, it feels bad :).

Recommended Posts

Let's write class __str__ more easily using lambda!
Easily write if-elif with lambda
Let's easily make a math gif using Google Colaboratory