为什么 Python 数据类 "persist" 超出了其定义函数的范围?

Why does a Python dataclass "persist" outside the scope of its defining function?

考虑以下最小示例:

>>> 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() 打印的值都会增加? stuff 是否应该在 my_func() 执行完成后超出范围?并且每次调用 my_func() 不应该创建一个新实例 my_variable 每次初始化为 0 并递增到 1 吗?

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

You are using Class itself Rather than instance!

class human:
    pass


human_kind = human #Pointer to class

print(human_kind)

alex = human() #Instance initializing

print(alex)

Results:

<class 'main.human'>

<main.human object at 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)