-3

I want to ask a question.

I made a ClassName.py and it has 'list Variable' like number = [].

And I push variables at list and make class objects which is list too in main function.

But now I am faced with a problem.

For example I make a object1 and it has list variable. After make object2 it has same variable object1. (object1 -> list Variable = [1,2,3,4,5] , object2 -> list Variable = [1,2,3,4,5])

More detailed, I want to add a '6' to object2 list. If I add '6' at object2 list the object1 list has added '6' too.

I don't know how I can solve the problem.

Plz. Give an advice

  • 3
    ....uhh.... wat – a p Jul 27 '17 at 01:37
  • 3
    Can you please show the actual code that replicates the problem you are experiencing please? It is not very clear what the problem is. – idjaw Jul 27 '17 at 01:37
  • 2
    Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – Maxime Franchot Jul 27 '17 at 01:39
  • It sounds like you need to read up on Python classes, because I think this problem could be fixed with a well-placed `self.` in front of some variable names. – Silvio Mayolo Jul 27 '17 at 01:41
  • I'm sorry. here is my github, https://github.com/dldudwo0805/DeepLearningPractice – Youngjae Lee Jul 27 '17 at 01:42
  • Please copy some of the relevant class code into your question text. It'll make it way easier for any future readers who come upon this page looking for solutions to similar problems. – Silvio Mayolo Jul 27 '17 at 01:45

2 Answers2

1

That's because you put the variables to be class-level. Thus, all the instances share the value of those variables.
To solve this, put the list variables inside __init__(self), like this:

class YourClassName:
    #Don't put it here!
    def __init__(self):
        self.your_list_name = [] #Put it here
Hou Lu
  • 3,012
  • 2
  • 16
  • 23
0

The repository you linked has code that looks like this.

class Foo:
    a = 1
    b = 2
    def __init__(self):
        ...

This is creating class variables called a and b. If you're familiar with a language like Java, this is the nearest equivalent of static variables in other languages. What you want is an instance variable, and we always prefix those with self., as well as defining them within __init__, not at class scope.

class Foo:
    def __init__(self):
        self.a = 1
        self.b = 2
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • I'm sorry i don't understand what you said. I make 'class', and make '__init__(self):' like you said. If you saw my code, see the 'x_point', 'y_point', and 'data_type', there is list variable, so i want to add data at them. if I make 3 class object, all class object has same list variable. This is the problem – Youngjae Lee Jul 27 '17 at 01:51