Python中的身份比较(is|=)

is

在python中,isis not用于测试对象(object)的身份。

对象的身份用id()来决定

=

=即赋值,用于传递参数,将右边的参数传递给左边

  1. 传入的参数实际上是对对象的引用(但引用是按值传递的)
  2. 一些数据类型是可变的,但其他不可变
  3. 如果将一个参数传递进函数,可以随心所欲的更改可变对象,但是一旦在函数中重新绑定引用,外部作用域将一无所知,完成后,外部作用域仍将指向原对象,即原对象不会更改

=表示对参数的引用,而不是它的副本,可以通过方法(append等)来更改它,并将更改反射回去

def try_to_change_list_reference(the_list):
    print('got', the_list)
    the_list = ['and', 'we', 'can', 'not', 'lie']
    print('set to', the_list)

outer_list = ['we', 'like', 'proper', 'English']

print('before, outer_list =', outer_list)
try_to_change_list_reference(outer_list)
print('after, outer_list =', outer_list)
Output:

before, outer_list = ['we', 'like', 'proper', 'English']
got ['we', 'like', 'proper', 'English']
set to ['and', 'we', 'can', 'not', 'lie']
after, outer_list = ['we', 'like', 'proper', 'English']

相关连链接: https://stackoverflow.com/questions/986006/how-do-i-pass-a-variable-by-reference

猜你喜欢

转载自blog.csdn.net/majiayu000/article/details/129679817