H S
H S

Reputation: 23

Python class initialization for newbie

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'

Upvotes: 2

Views: 96

Answers (1)

novaXire
novaXire

Reputation: 136

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..

Upvotes: 2

Related Questions