0

Please look at the code snippet below, I asked the question below

class SAMPLES:
    x = np.zeros(10)

    def __init__(self, k, value):
        self.x[k] = value


a = SAMPLES(0, 9)
b = SAMPLES(0, 10)
print(a.x[0])
print(b.x[0])

OUTPUT:

10
10

But the output must be:

9
10

How should I solve this problem?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
mehran
  • 191
  • 10
  • 3
    Put `self.x = np.zeros(10)` in the `__init__` method. Using a class attribute shares the same array for all instances. – Barmar Jun 02 '22 at 18:04
  • 3
    you're using a _class variable_ but you want an _instance variable_. `x` has the same underlying data across all instances of `SAMPLES`. – jkr Jun 02 '22 at 18:04
  • 1
    `x` has been declared as a static variable instead of a instance variable. [see this](https://stackoverflow.com/questions/68645/static-class-variables-and-methods-in-python) – Blackgaurd Jun 02 '22 at 18:04
  • Thank you all, I noticed the problem – mehran Jun 02 '22 at 18:09
  • 1
    I edited the title to better express the problem because at first glance I thought you were simply asking how to instantiate a class. But if you want to [edit] it further, by all means. Check out [ask] if you want tips. – wjandrea Jun 02 '22 at 18:10
  • 1
    @wjandrea, Yes, the title you wrote is correct. thank you so much. – mehran Jun 02 '22 at 18:14

1 Answers1

6

Declare x within the __init__ method.

class SAMPLES:
    def __init__(self, k, value):
        self.x = np.zeros(10)
        self.x[k] = value


a = SAMPLES(0, 9)
b = SAMPLES(0, 10)
print(a.x[0])
print(b.x[0])
Blackgaurd
  • 608
  • 6
  • 15
  • 1
    Correction: *declare* -> *define*. Python only has declarations for scope (`global` and `nonlocal`), which aren't being used here. – wjandrea Jun 02 '22 at 18:13