python3中的lambda如何处理参数引用?

2024-05-14 13:04:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习flask,现在我正在阅读flask代码。
我遇到了一个我不能完全理解的障碍。你知道吗

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__())

第一次打印将lambda方法显示为:

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

第二条:

<__main__.Test object at 0x7fcc4394d210>

那么funcimplements_to_string中lambda中的x何时成为cls对象呢?
这只是我现在需要记住的内在机制吗?
或者背后还有什么需要知道的?你知道吗


Tags: tolambdatestflaskstringobjectmaindef
1条回答
网友
1楼 · 发布于 2024-05-14 13:04:26

根据文件:

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.

您对implements_to_string的实现与我这里的类似:

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?

当您使用print(test.__str__)时,您正在打印方法本身,并打印其表示形式。你知道吗

但是当您使用print(test.__str__())时,您首先执行函数并打印方法返回的内容。你知道吗

相关问题 更多 >

    热门问题