简单的例子.两种方法,一种叫另一种方法:
def method_a(arg):
some_data = method_b(arg)
def method_b(arg):
return some_data
Run Code Online (Sandbox Code Playgroud)
在Python中,我们可以def在另一个内部声明def.因此,如果method_b需要并且仅从中调用method_a,我应该method_b在内部声明method_a吗?像这样 :
def method_a(arg):
def method_b(arg):
return some_data
some_data = method_b
Run Code Online (Sandbox Code Playgroud)
或者我应该避免这样做?
该id()内置功能使...
一个整数(或长整数),保证在该生命周期内该对象是唯一且常量的.
该is操作,相反,给...
对象身份
那么,为什么有可能有具有相同的两个对象id,但返回False到is检查?这是一个例子:
>>> class Test():
... def test():
... pass
>>> a = Test()
>>> b = Test()
>>> id(a.test) == id(b.test)
True
>>> a.test is b.test
False
Run Code Online (Sandbox Code Playgroud)
一个更令人不安的例子:(继续上述)
>>> b = a
>>> b is a
True
>>> b.test is a.test
False
>>> a.test is a.test
False
Run Code Online (Sandbox Code Playgroud)
然而:
>>> new_improved_test_method = lambda: None
>>> a.test = new_improved_test_method
>>> a.test is a.test
True
Run Code Online (Sandbox Code Playgroud) 在Python中,可以嵌套这样的函数:
def do_something():
def helper():
....
....
Run Code Online (Sandbox Code Playgroud)
除非Python更巧妙地处理这种情况,否则helper每次都必须重新创建do_something.事实上,这样做会影响性能,而不是在主要功能之外创建辅助功能,如果是的话,它有多棒?