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?

6
  • 3
    Put self.x = np.zeros(10) in the __init__ method. Using a class attribute shares the same array for all instances. Commented Jun 2, 2022 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. Commented Jun 2, 2022 at 18:04
  • 1
    x has been declared as a static variable instead of a instance variable. see this Commented Jun 2, 2022 at 18:04
  • 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 How to Ask if you want tips. Commented Jun 2, 2022 at 18:10
  • 1
    @wjandrea, Yes, the title you wrote is correct. thank you so much. Commented Jun 2, 2022 at 18:14

1 Answer 1

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])
Sign up to request clarification or add additional context in comments.

1 Comment

Correction: declare -> define. Python only has declarations for scope (global and nonlocal), which aren't being used here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.