简体   繁体   English

python对象作为函数的参数

[英]python object as argument of a function

I know that python pass object by reference, but why the second output of codes below is 3 other than 10? 我知道python通过引用传递对象,但是为什么下面代码的第二个输出是10以外的3?

class a():
    def __init__(self, value):
        self.value = value

def test(b):
    b = a(10)

b = a(3)
print(b.value)
test(b)
print(b.value)

Python objects are passed by value, where the value is a reference. Python对象按值传递,其中值是引用。 The line b = a(3) creates a new object and puts the label b on it. b = a(3)创建一个新对象,并在其上放置标签b b is not the object, it's just a label which happens to be on the object. b不是对象,它只是碰巧在对象上的标签。 When you call test(b) , you copy the label b and pass it into the function, making the function's local b (which shadows the global b ) also a label on the same object. 调用test(b) ,您将复制标签b并将其传递给函数,从而使函数的局部b (遮盖全局b )也成为同一对象上的标签。 The two b labels are not tied to each other in any way - they simply happen to both be currently on the same object. 两个b标签没有以任何方式彼此绑定-它们只是碰巧当前都位于同一对象上。 So the line b = a(10) inside the function simply creates a new object and places the local b label onto it, leaving the global b exactly as it was. 因此,函数内部的b = a(10)行仅创建了一个新对象并将本地b标签放置在其上,而使全局b原样。

  1. You did not return a value from the function to put into the class. 您没有从函数中返回要放入类的值。 This means the 'b' is irrelevant and does nothing. 这意味着“ b”是无关紧要的,什么也不做。 The only connection is the name 'b' 唯一的连接是名称“ b”

  2. You need to reassign the value 'b' to be able to call the class. 您需要重新分配值“ b”才能调用该类。

class a(): a()类:

def __init__(self, value):
        self.value = value

def test(b):
    b = a(10)
    return b

b = a(3)
print(b.value)

b = test(3)
print(b.value)

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

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