0

I'm new to python. When I code in Python I notice this strange behavior:

Class x:

class x:
    x1 = 0

    def __init__(self, x):
        self.x1 = x

Class xcontainer:

class xContainer:
    coint = []

    def __init__(self, coint = []):
        self.coint = coint

    def add_x(self, x):
        self.coint.append(x)

when I try to run this code:

def Main():
    list_xcon = []
    for i in range (0,2):
        xcon = xContainer()
        for j in range (i, i+1):
            xcon.add_x(x(j))
        list_xcon.append(xcon)

    for xcont in list_xcon:
        for xc in xcont.coint:
            print xc.x1

I get those results:

0 1 0 1

but when I run this code:

def Main():
    list_xcon = []
    for i in range (0,2):
        listt = []
        xcon = xContainer(listt)
        for j in range (i, i+1):
            xcon.add_x(x(j))
        list_xcon.append(xcon)

    for xcont in list_xcon:
        for xc in xcont.coint:
            print xc.x1

I get those results:

0 1

Why is that? According to class xcontainer, the default of coint should be [] - empty list. So why sending empty list change the result?

By the way, I read that using coint = None as default and checking if coint is None: coint = [] is better way, but it seems that it does not change the results here.

I will appreciate any explanation. I'm confused.

Thanks.

Moshe9362
  • 352
  • 2
  • 15
  • 2
    Because you're using a *mutable default argument* in your `__init__` – Moses Koledoye May 13 '17 at 23:59
  • 2
    Also, stop creating class-level variables (you could call them "static") that you then immediately shadow on each instance in your initializers. Python != Java – juanpa.arrivillaga May 14 '17 at 00:01
  • @MosesKoledoye didn't know this so I didn't know that exactly to search to find the answer. It really is duplicate and can be closed. Thanks. – Moshe9362 May 14 '17 at 00:10
  • @juanpa.arrivillaga well as I said, I really am new to this language and I did code in java most of the time. thanks, it really helpful advice. – Moshe9362 May 14 '17 at 00:12
  • 1
    It is a very common mistake. Java's class system is more like C++, whereas Python's [class semantics are closer to Simula3/Smalltalk](https://docs.python.org/3/tutorial/classes.html). I think you will find that Python is actually quite straightforward if you don't bring in any of your assumptions from Java. Everything definined at the class level *belongs to the class*, and keep in mind, in Python, classes are just another object. Anything assigned to `self` inside a method will belong to the *instance*. – juanpa.arrivillaga May 14 '17 at 00:19

0 Answers0