Francisco Aguilera
Francisco Aguilera

Reputation: 147

List appending appends more values than expected

I tried to do a function that takes a list of messages and a list of authors, and puts every message in it's corresponding author's message list.

class Author:
    name = ""
    msgs = []
    files = []

class Message:
    line = ""
    time = datetime
    author = ""

Function mentioned

for au in authorList:
    a = 0
    for msg in msgList:
        if au.name == msg.author:
            a += 1
            au.msgs.append(msg)
    print(a)

for au in authorList:
    print(len(au.msgs))

And the output of the program

a=396
a=349
745
745

The function takes au.name and msg.author and compares them, if they are equal, the msg is stored in au.msgs list.

The variable a is incremented everytime a message is added to the user, and as it can be seen, for the first user a = 396 and for the second user a = 349 which sum 745, which is the size of the msgList.

The problem is that each author.msgList ends holding the total number of messages.

I have to mention that I am low skilled in python, so it might be a simple noob problem.

Upvotes: 0

Views: 70

Answers (1)

Guybrush
Guybrush

Reputation: 2780

That's because the msgs and files are class variables, not instance variables, so they are shared by all instances of Author.

You can define them as instance variables as follows:

class Author:
  def __init__(self):
    self.name = ''
    self.msgs = []
    self.files = []

As suggested by TheGamer007, consider having a look at https://www.geeksforgeeks.org/g-fact-34-class-or-static-variables-in-python/

Upvotes: 3

Related Questions