-2

Look at the code below:

class Node:
    feature = list()
    label = list()

    def __init__(self, f, l):
        self.feature.append(f)
        self.label.append(l)

I create two instances of this class:

n1 = Node(1,2)
print n1.feature

n2 = Node(3,4)
print n2.feature

My desired output is:

1
2

But the real output is:

1
1 2

What is the problem? How can I fix it?

Moh
  • 1,887
  • 3
  • 18
  • 29

2 Answers2

2

variables defined in class scope are class variables, and are share among all class instances (they are stored on the class object itself, not on the instances). Just initialize the variables inside the init function.

class Node:    
    def __init__(self, f, l):
        self.feature = [f]
        self.label = [l]
eran
  • 6,731
  • 6
  • 35
  • 52
1

The issue is that you're trying to "declare" the member data for the class instances in the class block. That's not how Python works.

Everything defined in the class block (including feature, label, and __init__) becomes an attribute of the object that represents the class itself, not the instances of the class. Trying to access an attribute that doesn't exist in an instance will fall back to the class, which is how method lookup works.

There is no way to create a attribute on an instance until it exists and you have a reference to it. The purpose of the __init__method is to give you a place to do that. So initial values for an instance's member data should be set up in __init__; trying to declare these initial values in the class block actually does something else.

Ben
  • 68,572
  • 20
  • 126
  • 174