【问题标题】:Why does a Python dataclass "persist" outside the scope of its defining function?为什么 Python 数据类在其定义函数的范围之外“持续存在”?
【发布时间】:2021-08-24 00:33:13
【问题描述】:

考虑以下最小示例:

>>> from dataclasses import dataclass
>>> @dataclass
... class my_stuff:
...     my_variable: int = 0
...
>>> def my_func():
...     stuff = my_stuff
...     stuff.my_variable += 1
...     print(stuff.my_variable)
...
>>> my_func()
1
>>> my_func()
2
>>> my_func()
3

为什么每次调用my_func() 时打印的值都会增加?一旦my_func() 的执行完成,stuff 是否应该不超出范围?并且每次对my_func() 的调用不应该创建一个my_variable 初始化为0 并每次递增为1 的新实例吗?

我将如何更改此代码以满足我的(显然是不合理的)期望,即每次调用 my_func() 时都会输出 1?

【问题讨论】:

  • 尝试将 stuff = my_stuff 替换为 stuff = my_stuff() 以每次实例化一个新对象,而不是修改类本身。
  • stuff.my_variable 其中stuff=my_stuff 修改类属性值。 IE。您的代码按预期工作,而您对不同事物的期望/假设是不合理的。
  • 要调试这类问题,本例打印stuff函数中;你会看到它是类定义。
  • stuff 只是 my_stuff 的另一个名称。一个名称超出范围不会影响对象本身。

标签: python scope python-dataclasses


【解决方案1】:

您使用的是类本身而不是实例!

class human:
    pass


human_kind = human #Pointer to class

print(human_kind)

alex = human() #Instance initializing

print(alex)

结果:

ma​​in.human'>

ma​​in.human 对象位于 0x7fd11ce47100>

真实代码:

from dataclasses import dataclass


@dataclass
class my_stuff:
    my_variable: int = 0


def my_func():
    stuff = my_stuff()
    stuff.my_variable += 1
    print(stuff.my_variable)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-18
    • 2014-05-26
    • 2020-01-18
    • 2018-10-18
    • 1970-01-01
    • 2014-05-03
    相关资源
    最近更新 更多