1

I have the following class:

import random as rd

class Human():
    def __init__(self,name,testList=[]):

        self.name = name
        self.testList = testList

    def fill_list(self):

        self.testList.append(rd.choices([0,1],weights= [0.75,0.25],k=10))

and a corresponding main file that initiates two instances of the class and puts them in a list:

from testtest import Human

foo = Human("Bar")
faa = Human("Bor")


check = []
check.append(foo)
check.append(faa)


for entry in check:
    entry.fill_list()

for entry in check:
    print(entry.name,entry.testList)

when I run the main file I get the following output:

Bar: [[0, 0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]]
Bor: [[0, 0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0]]

Two questions:

  1. Why do both instances have the exact same list even-though they are randomly generated?
  2. At what point does it call the method twice per instance?

Thanks a lot for your feedback in advance!

Difio
  • 145
  • 8
  • It is at first hard to understand. But if you declare a variable inside a class. The variable is a class member and not an instance member! That is why the default-value [] for testList is not valid, since there is already a value present for testList. You need to make sure in __init__ that a new instance of the variable is being created. ``` lang-python class Human(): def __init__(self,name): self.name = name self.test_list = [] def fill_list(self): self.test_list.append(rd.choices([0,1],weights=[0.75,0.25],k=10)) ``` – Miller-STGT Dec 26 '21 at 16:24
  • @Miller That explanation is also pretty hard to understand…‽ – deceze Dec 26 '21 at 16:26
  • Does this help? https://stackoverflow.com/questions/1680528/how-to-avoid-having-class-data-shared-among-instances – Miller-STGT Dec 26 '21 at 16:31
  • Thanks so much for your feedback! Didn't realise you could comment when the answer was already closed. Damn I had no idea variables become class members. The issue is in my practical case, that I need the option of instancing the testList. Is there anyway around that? – Difio Dec 26 '21 at 17:39
  • You did read the duplicate…? https://stackoverflow.com/a/11416002/476 – deceze Dec 26 '21 at 18:46
  • Yes but unfortunately the penny didn't drop for me while reading it. :( – Difio Dec 27 '21 at 12:55
  • Do not use `def func(arg=[])`. Instead, use `def func(arg=None)` and then `if arg is None: arg = []` in the function body. – g.d.d.c Jan 08 '22 at 02:58

0 Answers0