2

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
asked Nov 9, 2020 at 14:41
4
  • 1
    Why are you using B.c? There is only one of those. Commented Nov 9, 2020 at 14:43
  • 2
    And actually, I'm surprised you are getting any output. You should always fail here: test_list.append(B(row[0], row[1], row[2])) because the B constructor only takes two arguments, but you are passing 3. You really should do something like try: ... except: pass. Commented Nov 9, 2020 at 14:45
  • 1
    I strongly suspect that when you write A.a = a, you really mean self.a = a. Same goes for instances of B.b and B.c. Commented Nov 9, 2020 at 14:46
  • Yep guys you are right. I've missed 'a' while copying the code here. In my initial code 'a' is present in class 'B' Commented Nov 10, 2020 at 6:31

1 Answer 1

2

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
answered Nov 9, 2020 at 14:47
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.