Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I have 2 after second call?

Tags:

python

class s:
    i = []

def inc():
    t = s()
    t.i.append(len(t.i))
    return len(t.i)


print(inc())
print(inc())

my output:

1
2

but I expected:

1
1

becouse everytime created new object, where my mistake?

like image 904
Gulaev Valentin Avatar asked Jan 21 '26 03:01

Gulaev Valentin


1 Answers

You are appending to a variable of the class, not a variable of the instance

class s:
    i = []

This code creates a variable in the class. This is similar to the concept of a static variable in Java or C++.

In java:

class S {
    static List i = new ...
    }

You probably wanted to do this:

class s:
    def __init__(self):
        self.i = []

This creates a variable in the instance, which is named self (similar to this in Java or C++). __init__ is the constructor of the class.

like image 120
loopbackbee Avatar answered Jan 23 '26 17:01

loopbackbee