-1

I have the following class. Every instance of the class that I create is having the same copy of the list field

class Vertex:
    label = None
    data = None
    connected_vertices_ids = []

    def __init__(self, data):
        self.data = data
        self.label = randint(1, 100)

    def __init__(self, vertex_id, data):
        self.data = data
        self.label = vertex_id

    def print_vertex(self):
        print(self.label, self.connected_vertices_ids)

Usage

arr = []
arr.append(Vertex('Tampa', None))
arr.append(Vertex('Clearwater', None))
arr.append(Vertex('St. Pete', None))
arr.append(Vertex('Largo', None))
arr.append(Vertex('Seminole', None))
arr.append(Vertex('Orlando', None))
for vertex in arr:
    print(id(vertex), id(vertex.connected_vertices_ids))

Result

140582021542688 140582025347656
140582021542744 140582025347656
140582021542800 140582025347656
140582021542856 140582025347656
140582021542912 140582025347656
140582021542968 140582025347656

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
lalatnayak
  • 160
  • 1
  • 6
  • 21
  • 1
    @depperm: it is an identifier of the *object* and is more or less the memory address where the object is stored. – Willem Van Onsem Jan 16 '17 at 17:53
  • 1
    You have two constructors? Is that even allowed? – Tagc Jan 16 '17 at 17:57
  • You are right right it's not allowed to have multiple constructors in python. Not sure why this did not blow up then. However it was not causing the issue that I posted. I posted an answer. If you have anything to add please do. – lalatnayak Jan 16 '17 at 18:00

1 Answers1

0

My bad. I'm new to python and I'm not familiar with the memory model. I think fields that are initialized outside of a constructor behave as static. As soon as I changed the class code to the following, the issue was resolved

class Vertex:
    label = None
    data = None
    connected_vertices_ids = None

    def __init__(self, data):
        self.data = data
        self.label = randint(1, 100)
        self.connected_vertices_ids = []

    def __init__(self, vertex_id, data):
        self.data = data
        self.label = vertex_id
        self.connected_vertices_ids = []

    def print_vertex(self):
        print(self.label, self.connected_vertices_ids)

If anyone could answer this question more formally, I'd appreciate

Tagc
  • 8,736
  • 7
  • 61
  • 114
lalatnayak
  • 160
  • 1
  • 6
  • 21
  • Ensure your code has correct indentation when you copy it into your posts please. – Tagc Jan 16 '17 at 17:59
  • 2
    You're also correct in your reasoning. `connected_vertices_id` was declared and assigned as attributes of the `Vertex` *class*, so it was essentially a single static property being used by all instances. – Tagc Jan 16 '17 at 18:01