首页 > 解决方案 > Python类替换不起作用

问题描述

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):
    x = given.get_foo()
    x += 10

    y = given.get_bar()
    y[0] += ' there'
    y = ['cool']

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

x = A(1, ['hello'])
print(x.get_bar())

为什么 print(x.get_bar()) 打印 hello ,而不是 'test' 当给定被 A(-10, ['test']) 替换?在类似这样的功能中,

def test(x):
    x = 4
    return x

x = 1
test(x)

x 被 4 替换,实际返回 4。

标签: python-3.x

解决方案


在您的第二段代码def test(x):中,您将输入覆盖为 4,无论您通过设置输入什么x = 4

在您的第一段代码中,do_that(given):当您调用 时,您实际上并没有调用该函数x.get_bar(),因此['hello']不会被 覆盖['test']。此外, wheregiven被定义为 内的变量def get_bar(given):,它从未被使用过。


推荐阅读