First I make a python file clss.py
class A:
def __init__(self, a):
A.a = a
class B(A):
def __init__(self, b, c):
B.b = b
if c:
B.c = c
else:
B.c = '0'
def get_list(csv_filename):
test_list = []
with open(csv_filename) as csv_file:
reader = csv.reader(csv_file, delimiter=';')
next(reader)
try:
for row in reader:
test_list.append(B(row[0], row[1], row[2]))
except:
pass
return test_list
Then I read a csv file from prog.py where some 'None' values exists and a lot of normal values:
from clss.py import *
test = get_list('my_file.csv')
for i in test:
print(i.c)
And it gives me all '0'
Josh Karpel
2,1752 gold badges13 silver badges21 bronze badges
1 Answer 1
When you write B.c = '0', you set the variable at the class level, so all your objects will have the same value.
Replace all B. with self. in your class B. The same for class A with A..
Tomerikoo
19.6k16 gold badges57 silver badges68 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
lang-py
B.c? There is only one of those.test_list.append(B(row[0], row[1], row[2]))because theBconstructor only takes two arguments, but you are passing 3. You really should do something liketry: ... except: pass.A.a = a, you really meanself.a = a. Same goes for instances ofB.bandB.c.