-3

Consider the following minimal example:

>>> 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

Why does the printed value increase with each call to my_func()? Should stuff not go out of scope once the execution of my_func() is complete? And should each call to my_func() not create a new instance with my_variable initialized to 0 and incremented to 1 each time?

How would I change this code to meet my (apparently irrational) expectation that 1 would be output each time my_func() is called?

1 Answers1

0

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>

true code:

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)
Hamed Rostami
  • 1,670
  • 14
  • 16