python-3.x - 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。
解决方案
在您的第二段代码def test(x):
中,您将输入覆盖为 4,无论您通过设置输入什么x = 4
。
在您的第一段代码中,do_that(given):
当您调用 时,您实际上并没有调用该函数x.get_bar()
,因此['hello']
不会被 覆盖['test']
。此外, wheregiven
被定义为 内的变量def get_bar(given):
,它从未被使用过。
推荐阅读
- c - 将光标移动到ncurses窗口中一行文本的末尾?
- android-studio - 防止 Android Studio 将 jcenter 添加到 build.gradle
- memory - hyperbus内存结构如何?
- ios - 后台提取停止在 ios 13 及更高版本上工作
- python - 我可以为我的 Flask 应用程序工厂使用 app.py 而不是 __init__.py 吗?
- python - 按键从字典中提取值,字符串索引必须是整数
- microsoft-graph-api - 如何通过 Microsoft Graph 检查密码写回连接状态?
- python - 我如何告诉 sympy i^2 = -1?
- java - Java HashSet 使用其哈希码删除项目
- python - 输入布尔值(python)