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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With