0

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?

Bruno Fauth
  • 47
  • 10

3 Answers3

3

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
nbryans
  • 1,507
  • 17
  • 24
2

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.

Anonymous
  • 11,740
  • 3
  • 40
  • 50
  • I don't think this solves the case when he would like to assign the value himself (although it does seem redundant to pass a value only to immediately return it). – nbryans Jun 15 '16 at 12:56
  • I think that OP also wanted default argument for the "luck" function. – user1308345 Jun 15 '16 at 12:56
  • I thought so too, but that would defeat the purpose of having a random number returned so assumed it was just done that way by accident (clearly OP is still learning). – Anonymous Jun 15 '16 at 12:59
0

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.

Neo
  • 3,534
  • 2
  • 20
  • 32