python - 无法理解 python 中的某些类代码

标签 python

我对编程还很陌生,在理解这段代码的输出时遇到了一些困难。

#testclass.py

class TestCount:
    count = 0
    def __init__(self):
        self.attr1 = TestCount.count
        self.attr2 = TestCount.count + 1
        TestCount.count += 2

x = TestCount()
y = TestCount()

print(x.attr1, x.attr2)
print(y.attr1, y.attr2)

这是我目前正在学习的一本书中一个更大示例的重写。当运行此代码时,它给出:

0 1
2 3

当我期望它是:

0 1
0 1

我在这里缺少的基本原理是什么?我将 y 视为一个新实例,但它似乎正在从 x 停止的地方继续。抱歉,如果我没有清楚地解释自己,但我是新手。

最佳答案

count的属性,而不是实例的属性。这意味着该值由所有实例共享

您正在使用 TestCount.count 初始化 attr1,然后将其增加 2。因此,第二个实例将从将 attr1 设置为 2 开始,对于第三个实例 4,依此类推。

如果您希望使用 01 初始化两个属性(attr1attr2),您应该这样做:

class TestCount:
    def __init__(self):
        self.attr1 = 0
        self.attr2 = 1

矿石信息,建议阅读Classes官方 Python 教程中的部分。

关于python - 无法理解 python 中的某些类代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5925017/

相关文章:

python - 具有同一字符的多个实例的子字符串

python - 从父类(super class)实例化子类

python - 两件事 : 1) Printing errors/tracebacks/exceptions to GUI and 2) The best way to utilize a script within a script

python - numpy 数组 - 替换某些值

python - 根据多个数据帧的公共(public)时间戳创建数据帧

python - 使用 Python 和 pyodbc 时到 SQL Server 的域名和连接字符串

python - 使用 argparse 根据标志覆盖变量,如果没有给出参数则使用默认值 (python)

python - 如何将 python 字典放入 protobuf 消息中?

python - 如何将装饰器应用到每个 Flask View

python 节俭错误 ```TSocket 读取 0 个字节 ```