Answer the question
In order to leave comments, you need to log in
How to avoid static lists in python classes?
#!/usr/bin/python3
import random
class Vector:
element = []
N = 0
def __init__(self, N):
for i in range(N):
self.element.append(0)
self.N = N
def __str__(self):
out_str = ""
for i in range(self.N):
out_str = out_str + str(self.element[i]) + " "
return out_str
def generate(self):
random.seed()
for i in range(self.N):
self.element[i] = float(random.randint(1, 100))
first = Vector(3)
first.generate()
print(first)
second = Vector(3)
second.generate()
print(first)
print(second)
Answer the question
In order to leave comments, you need to log in
When you declare member variables, as you did, they are associated with the class, not the object. Similar to C++, you've made the elements and N member variables static.
You need to create member variables in the constructor, not in the class definition:
class Vector:
def __init__(self, N):
self.elenent = []
self.N = N
for i in range(N):
self.element.append(0)
def __str__(self):
out_str = ""
for i in range(self.N):
out_str = out_str + str(self.element[i]) + " "
return out_str
def generate(self):
random.seed()
for i in range(self.N):
self.element[i] = float(random.randint(1, 100))
class Vector:
__slots__ = ['element', 'N']
def __init__(self, N):
self.elenent = []
self.N = N
for i in range(N):
self.element.append(0)
def __str__(self):
out_str = ""
for i in range(self.N):
out_str = out_str + str(self.element[i]) + " "
return out_str
def generate(self):
random.seed()
for i in range(self.N):
self.element[i] = float(random.randint(1, 100))
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question