This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: New class instance not initializing variables of type list
Type: behavior Stage: resolved
Components: Versions: Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Arturo Inzunza, ammar2
Priority: normal Keywords:

Created on 2018-12-08 00:26 by Arturo Inzunza, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (2)
msg331370 - (view) Author: Arturo Inzunza (Arturo Inzunza) Date: 2018-12-08 00:26
List type variables in a class are not reset on new instances of the class.

Example: 

class Klazz:
    lst = []
    def __init__(self, va):
        print(self.lst)
        self.lst.append(va)


k = Klazz(1)
[]      -> This is correct as the lst value is empty on class instantiation

k2 = Klazz(2)
[1]   -> This is wrong, a totally new instance of the class retains the value of a previous class instance lst variable

k3 = Klazz(3)
[1, 2]  -> And so on... new instances all share the same list
msg331371 - (view) Author: Ammar Askar (ammar2) * (Python committer) Date: 2018-12-08 00:43
This is expected behavior, take a look at this section in the tutorial on classes: https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables

Unlike say Java, member variables need to be initialized in the constructor.
History
Date User Action Args
2022-04-11 14:59:09adminsetgithub: 79620
2018-12-08 00:43:21ammar2setstatus: open -> closed

type: behavior

nosy: + ammar2
messages: + msg331371
resolution: not a bug
stage: resolved
2018-12-08 00:26:46Arturo Inzunzacreate