D
D
Dmitry2015-04-25 12:04:27
Python
Dmitry, 2015-04-25 12:04:27

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)

On the output to the console I get:
38.0 41.0 82.0
34.0 42.0 34.0
34.0 42.0 34.0
Why do the values ​​of the list belonging to the first object change when calling the method of the second object? How to avoid?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander Movchan, 2015-04-25
@Liro

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

Or use the __slots__ special variable:
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))

The difference is that in the second case, you can no longer add other member variables, and the objects will take up less memory.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question