简体   繁体   English

Python嵌套函数不等于自身

[英]Python nested function is not equal to itself

This simple Python code gets "False".这个简单的 Python 代码得到“假”。

def foo():
    def bar():
        return 0
    return bar
print(foo() == foo())

When I request当我请求时

print(foo(),foo())

I get我得到

<function foo.<locals>.bar at 0x03A0BC40> <function foo.<locals>.bar at 0x03C850B8>

So does Python store the result of the bar function every time in the new memory slot?那么Python是否每次都将bar函数的结果存储在新的内存槽中呢? I'd be happy if someone explain how it works behind the scene and possibly how this code can be a little bit modified to get "True" (which still seems logical to me!).如果有人解释它在幕后是如何工作的,以及如何稍微修改这段代码以获得“真”(这对我来说仍然是合乎逻辑的!),我会很高兴。

Each def statement defines a new function.每个def语句定义一个新函数。 The same name and body doesn't really matter.相同的名字和身体并不重要。 You're basically doing something like this:你基本上是在做这样的事情:

def foo():
    pass

old_foo = foo

def foo():
    pass

assert old_foo == foo # will fail

bar is locally defined within foo the same way a local variable would be each time you call the foo() . barfoo本地定义,就像每次调用foo()时本地变量一样。

As you can see by the defult __repr__ , they have different memory addresses, and since bar does not implement __eq__ , the two instances of bar will not be equal.正如你可以通过defult看到__repr__ ,他们有不同的内存地址,因为bar没有实现__eq__ ,的两个实例bar将不相等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM