0

I did the following code,

class A:
    def __init__(self):
        self.a=[1,2,3,4,5,6,7,8,9,10,11,12,13,14]
        self.batch_size=5
        
    def next1(self,counter=count()):
        i = next(counter) * self.batch_size
        s = self.a[i:i + self.batch_size]
        
        return s

when I call next method by doing following

a=A()
a.next1()
#output [1,2,3,4,5]

b=A()
b.next1()
# output [6, 7, 8, 9, 10]

my question is why? as I am creating a new object so I am expecting same output[1,2,3,4,5] both the time. can anyone tell me where did I go wrong? I can not remove i function as it is connected to other part as well

Coder
  • 1,129
  • 10
  • 24
  • Even if it's not the cause of the problem, it's best not to name a method `next` as that's the name of a built-in function. – sj95126 Oct 29 '21 at 19:32
  • The linked dupe should explain more, but essentially `counter=count()` is only evaluated once (when the class is interpreted), not twice (once per instantiation). This is the 'mutable default argument' gotcha in Python. – Nathaniel Ford Oct 29 '21 at 19:37
  • @sj95126 i change the name of method, still out put remain the same – Coder Oct 29 '21 at 19:55
  • @NathanielFord could you explain bit more? – Coder Oct 29 '21 at 19:56

0 Answers0