I've just recently found this weird Python 'bug' and I wanted to see if anyone knew more about it!
for instance take the python module:
import random
class SaySomething:
def __init__(self, value=random.randint(1, 3)):
if value == 1: print 'one'
elif value == 2: print 'two'
elif value == 3: print 'three'
a = 0
while a < 10:
SaySomething()
a += 1
This code will for some reason print the SAME number 10 times!!! Now this I DO NOT understand. It seems that the constructor is being called with the same values 10 consecutive times. But if you print each SaySomething()
you'll see that they all have different pointer addresses, so they aren't the same object.
Now if you change:
SaySomething()
to
SaySomething(random.randint(1, 3))
It runs as expected, with actual random choices being made.
Anyone know why this happens?
The problem is that the default arguments in Python are evaluated once, when the function is created. To fix this, try:
def __init__(self, value = None):
if value is None:
value = random.randint(1, 3)
if value == 1: print 'one'
elif value == 2: print 'two'
elif value == 3: print 'three'
This way, we shift the randomization into the function itself, instead of at the time of function definition.
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