FrynioS FrynioS - 2 months ago 16
Python Question

Python class initialization - attributes memory

So I was writing a program in Python, which would take all my university classes (from csv) and print info about them. I've wrote a simple class

Subject
to manage everything better. In my uni there are classes in even weeks, odd weeks, and every-week classes, and I have lectures, exercises and laboratories. So my Subject class is like this:

class Subject:
number = 0
name = ""
dummyData = []
even = {}
odd = {}
all = {}
type = ""
def __init__(self, name, number, type):
self.name = name
self.number = number
self.type = type
self.info = str(number) + " " + name + " " + type


Previously I had all days written in
even
,
odd
, and
all
dicts, like this:

even = {"mon":"",
"tue":"",
"wed":"",
"thu":"",
"fri":"",
}


So I could add all the classes hours to specific day key. But, there was a problem. For example lets say Programming lecture is subject 1 and Programming laboratories are subject 2. Subject 1 is on Monday at 9.15. Subject 2 is on Monday as well, but at 17.05. So I have a function, which would check if the subject is on even/odd week or it is every week. And then I would assign f.e 9.15 to
even["mon"]
on subject 1. Then I would go for subject 2, and tried to add 17.05 to
even["mon"]
. Every subject was an other Subject class object stored in a list. But there was a mistake. When I tried to add 17.05 to subject 2s
even["mon"]
it added it, okay, but then
even["mon"]
should
="17.05"
, but it was
="9.15/17.05"
. I was trying to figure out whats wrong, and I finally did, by changing my class from:

class Subject:
number = 0
name = ""
dummyData = []
even = {"mon":"",
"tue":"",
"wed":"",
"thu":"",
"fri":"",
}
...etc...
type = ""
def __init__(self, name, number, type):
self.name = name
self.number = number
self.type = type
self.info = str(number) + " " + name + " " + type


to:

class Subject:
number = 0
name = ""
dummyData = []
even = {}
odd = {}
all = {}
type = ""
def __init__(self, name, number, type):
self.name = name
self.number = number
self.type = type
self.info = str(number) + " " + name + " " + type
self.even = {"mon":"",
"tue":"",
"wed":"",
"thu":"",
"fri":"",
}


+ odd and all. So why is Python like remembering whats been written into the first object attributes?

Answer

You need to declare the attributes inside the __init__ method. Here's an example

class Subject:
    def __init__(self, name, number, type):
       self.number = number
       self.name = name
       self.dummyData = []
       self.even = {}
       self.odd = {}
       self.all = {}
       self.type = type

Declaring the variables inside the class declaration makes them "class" members and not instance members. Declaring them in the __init__ method makes ensures a new instance of the members is created every time you create a new instance of the object.