0

I'm learning flask, and now I'm reading the flask code.
I come into a block that I can not understand completely.

def implements_to_string(cls):
    cls.__unicode__ = cls.__str__
    cls.__str__ = lambda x: x.__unicode__().encode('utf-8')
    return cls

@implements_to_string
class Test(object):
    def __init__ (self):
        pass

test = Test()
print(test.__str__)
print(test.__str__())

The first print shows the lambda method as:

<bound method Test.<lambda> of <__main__.Test object at 0x7f98d70d1210>>

The second:

<__main__.Test object at 0x7fcc4394d210>

So when does the x in the lambda in func implements_to_string become the cls object?
Is it just an inner mechanism I just need to remember now?
Or is there something else behind need to know?

2
  • The x parameter when calling the lambda function is not the Test class but the instance test. Python invokes instancemethods with the instance (self) as first argument. Commented May 13, 2016 at 9:36
  • @resi Thank you very much. I under stand now that the lambda function under a class environment will take the first param as self Commented May 13, 2016 at 10:02

1 Answer 1

1

From the documentation:

Small anonymous functions can be created with the lambda keyword. This function returns the sum of its two arguments: lambda a, b: a+b. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition.

Your implementation of implements_to_string is similar to what I have here:

def implements_to_string(cls):
    cls.__unicode__ = cls.__str__

    def lambda_func(self):
        return self.__unicode__().encode('utf-8')

    cls.__str__ = lambda_func
    return cls

So when does the x in the lambda in func implements_to_string become the cls object?

When you use print(test.__str__) you are printing the method itself and its representation is printed.

But when you use print(test.__str__()) you are first executing the function and printing what is returned by the method.

Sign up to request clarification or add additional context in comments.

3 Comments

You may want to use the conventional self variable name instead of x in the included code snippet to make it even clearer what is going on.
I figure out now that the first param in lambda under class circumstance will be treated as self as in normal function. Thank you @AKS and @Martin.
I just used x to keep it closer to what the user have in the snippet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.