繁体   English   中英

此代码示例中的['boo there']来自哪里?

[英]Where does the ['boo there'] come from in this code example?

我在这里有此功能,我正在努力弄清楚如何从中获得输出。 任何帮助,将不胜感激。 谢谢!

class A:
    def __init__(self, a: int, b: [str]):
        self._foo = a
        self._bar = b

    def get_foo(self):
        return self._foo

    def get_bar(self):
        return self._bar



    def do_that(given: A):
        x = given.get_foo()
        x += 10
        y = given.get_bar()

        y[0] += ' there'

        y = ['cool']

        given = A(-10, ['bye'])


x = A(1, ['boo'])
print(x.get_foo())
print(x.get_bar())
do_that(x)
print(x.get_foo())
print(x.get_bar())

有人可以解释为什么这是输出吗? ['boo there']来自哪里,在那之前是1?

1
['boo']
1
['boo there']

您看到的问题是在do_that函数中,您从self._fooself._bar获取xy 您修改两个局部变量。 但是,当您再次打印它们时,只有self._bar改变了。

这是因为在python中, list类型是可变的(可以更改),而int类型是不可变的(只能被替换)。

这意味着,当将y self._bar并将"there"添加到元素[0] ,它实际上是在更改self._bar属性所保存的列表值。

但是由于self._foo只是一个不可变的值类型,因此将其分配给变量x并更改x只会导致x发生更改,而不是原始的self._foo

如果要更改实例属性,正确的编程将让您说出self._foo += 10

当您在do_that()方法中调用y = given.get_bar()时, get_bar()实际上会返回_bar列表引用的引用。 由于列表是可变的,因此它通过引用传递。

并且当您执行操作y[0] += ' there'它实际上会更改_bar列表,因为y是_bar的引用及其可变对象,并成为['boo there'] 但是,当您执行y = ['cool'] ,实际上会创建一个新的列表引用,因此_bar先前的引用丢失了。 因此,它将不再更改_bar

结果是,当您调用x.get_bar()do_that()方法返回后,其结果为['boo there']

暂无
暂无

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

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