0

below java code will print two lists with A and B values.

import java.util.ArrayList;

public class MyClass {

    private String value;
    private ArrayList<String> ss = new ArrayList<>();

    public MyClass(String value) {
        this.value = value;
    }

    public void initialize(){
        this.arrayList.add(this.value);
    }

    public static void main(String[] args) {
        MyClass a = new MyClass("A");
        a.initialize();
        System.out.println(a.ss);

        MyClass b = new MyClass("B");
        b.initialize();
        System.out.println(b.ss);
    }
}

output as expected:

[A]
[B]

so, the python solution should return same results but it doesn't work.

class MyClass:
    ss = []
    value = None

    def __init__(self, value):
        self.value = value

    def initialize(self):
        self.ss.append(self.value)


a = MyClass("A")
a.initialize()
print(a.ss)

b = MyClass("B")
b.initialize()
print(b.ss)

output:

['A']
['A', 'B']

I don't know why object a infers on object b. Looks like for object b the ss variable is already filled with values from object a. How can I solve this problem? I am learning python but this behavior doesn't exist in java.

A S
  • 3
  • 2
  • 1
    Please think on this daily: java is not python. Every language is different from every other language, and trying to think of them in the same way is just another way to hurt your brain. – NomadMaker Feb 23 '21 at 23:22

1 Answers1

2

In python, we write

class MyClass:

    def __init__(self, value):
        self.ss = []
        self.value = value

    def initialize(self):
        self.ss.append(self.value)


a = MyClass("A")
a.initialize()
print(a.ss)
# ['A']    

b = MyClass("B")
b.initialize()
print(b.ss)
# ['B']

The way you had defined it, ss was treated as a static variable.

Generally speaking you refer to static variables in python by writing MyClass.ss instead of self.ss. As per this answer:

Variables declared inside the class definition, but not inside a method are class or static variables

Which was your problem.

Kraigolas
  • 5,121
  • 3
  • 12
  • 37