简体   繁体   中英

How do I create a new object for each class instance?

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM