Bruno Fauth
Bruno Fauth

Reputation: 57

Getting a random number each time in a script

I'm having trouble with the following bit of code:

from random import randint
class character():
    __init__(self):
        #init stuff here
    def luck(self, Luck = randint(0, 3)):
        return Luck

I have to call this method multiple times in my script, for multiple instances, to get a different number each time. The problem that I'm having is that whenever i call this method, no matter from what instance, I always to get the same result. For example, in the following code:

Foo = character()
Bar = character()
for foobar in range(3):
    print(Foo.luck(), Bar.luck())

I'd get as my output:

1 1
1 1
1 1

By the way, in my code, I used randint(0, 3) as an argument for the luck() method because, in some specific situations, I'd like to assign values to it myself.

Back to the point, how can I get a different number each time?

Upvotes: 0

Views: 1223

Answers (3)

nbryans
nbryans

Reputation: 1517

This is a definition for the luck function. If the user specifies a number it will be returned. If instead no argument is given, Luck will be set from randint and that random value returned.

def luck(self, Luck = None):
    if Luck is None:
        Luck = randint(0,3)
    return Luck

Upvotes: 3

Neo
Neo

Reputation: 3786

You can use None or something for a default argument, check if you got None and if you did - call randint() (if not just return what you did get).
If you use randint() in the function deceleration it will randomize it only once.

Upvotes: 0

Anonymous
Anonymous

Reputation: 12100

In python, the default expressions that set the default values for function arguments are only executed once. This means that once you define the luck method, whatever value randint() spit out the first time will stay for all invocations.

To get a new random number every time the method is called, you need to call it inside the body of the method:

class Character(object):
    @staticmethod # required if you're not accepting `self`
    def luck():
        return randint(0, 3)

This will work as expected.

Upvotes: 2

Related Questions