1

I need help with this issue: I've created a class whose reference is a random number. The problem is this: every time a call that class, i get the same number, making pointless the use of random; is there any way to solve this?

import random
class dicethrow:
    result = random.randint (1,6)
a = dicethrow ()
b = dicethrow ()

Using this, a == b always, i need them to be different. Thanks!

Tanke88
  • 11
  • 2
  • possible duplicate of [random.choice not random](http://stackoverflow.com/questions/1366047/random-choice-not-random) – bartimar Sep 30 '13 at 20:10

3 Answers3

2

In your case result is a class (or static) variable - it is defined once and is the same for all instances.

Define result in __init__() method:

import random


class dicethrow:
    def __init__(self):
        self.result = random.randint(1,6)

a = dicethrow()
b = dicethrow()
print a.result
print b.result

See also:

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
1

what about

class dicethrow:
    def __init__(self):
        self.result = random.randint(1, 6)
prgao
  • 1,767
  • 14
  • 16
  • so the problem is that as soon as i create the class, every reference is created; your way, every time i call the class, it creates the number, am I right? anyhow, it works, thanks! – Tanke88 Sep 30 '13 at 19:52
1

This is because result is a static variable, shared by all the instances of your class.

What you need here is a function:

import random
def dicethrow():
    return random.randint (1,6)
a = dicethrow ()
b = dicethrow ()
GL770
  • 2,910
  • 1
  • 14
  • 9