Python constructor weirdness

Question:

I have this simple code:

class bfs:
    vis=[]
    bags=[]
    def __init__ (self,x): 
        for i in p:    #initializes vis with len(p) zeroes 
            self.vis.append(0)
            print self.vis
        self.vis[x]=1   #marks index x as visited
        print self.vis

p=raw_input("Input values: ").split()
for i in range(0,len(p)):
    p[i]=int(p[i])

q=[]
for i in range(0,len(p)):
    q.append(bfs(i))

print
for i in q:
    print i.vis

If i input, say, any 3 numbers, why do I get this output:

[0]
[0, 0]
[0, 0, 0]
[1, 0, 0]
[1, 0, 0, 0]
[1, 0, 0, 0, 0]
[1, 0, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 0, 0, 0]
[1, 1, 0, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 0, 0, 0, 0, 0, 0]

[1, 1, 1, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 0, 0, 0, 0, 0, 0]
[1, 1, 1, 0, 0, 0, 0, 0, 0]

Instead of something like this?

[0]
[0, 0]
[0, 0, 0]
[1, 0, 0]
[0]
[0, 0]
[0, 0, 0]
[0, 1, 0]
[0]
[0, 0]
[0, 0, 0]
[0, 0, 1]

[1, 0, 0]
[0, 1, 0]
[0, 0, 1]

The program seems to just keep on working with one array in all created objs. Why is this the case?

Asked By: andrepd

||

Answers:

The problem is that you’re defining defining vis and bags as part of the class (as "attribute references"), instead of in the constructor. Try this instead:

class bfs:
    def __init__(self, x):
        self.vis = []
        self.bags = []
        # etc.

The documentation for class objects may help:

Attribute references use the standard syntax used for all attribute references in Python: obj.name. Valid attribute names are all the names that were in the class’s namespace when the class object was created. So, if the class definition looked like this:

class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        return 'hello world'

then MyClass.i and MyClass.f are valid attribute references, returning an integer and a function object, respectively. Class attributes can also be assigned to, so you can change the value of MyClass.i by assignment.

There’s also a Dive Into Python page about this:

Class attributes are available both through direct reference to the class and through any instance of the class.

Note: In Java, both static variables (called class attributes in Python) and instance variables (called data attributes in Python) are defined immediately after the class definition (one with the static keyword, one without). In Python, only class attributes can be defined here; data attributes are defined in the __init__ method.

Answered By: Brendan Long
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.