Xuan
Xuan

Reputation: 163

Function in python

I am trying to write a Linear congruential generator in python and I find a little piece of code on Wikipedia but have some difficulty on understanding it. The code is as follows:

def lcg(modulus, a, c, seed=None):
    if seed != None:
        lcg.previous = seed
    random_number = (lcg.previous * a + c) % modulus
    lcg.previous = random_number
    return random_number / modulus
lcg.previous = 2222

My problem is that what is "lcg.previous"? I notice that the function is done, the value of lcg.previous gets updated and stored. Is it declared as a member variable of function lcg() here or actually some kind of default set up for all function in python?

Thanks a lot!

Upvotes: 4

Views: 261

Answers (3)

John Percival Hackworth
John Percival Hackworth

Reputation: 11531

The previous variable is a property on the lcg function. In this example it's being used as a static variable for the lcg function. Since Python doesn't require variables (or object members) to be declared before use you can create them at need. In this case, you've create a member previous of the lcg function object.

Upvotes: 0

Stephan
Stephan

Reputation: 686

Python is recognizing the lcg.previous as a new variable declaration, and will add it as a member to lcg.

Upvotes: 0

Scott Hunter
Scott Hunter

Reputation: 49803

It is a "member variable" of the function, so that each time it is called (except when called with something for seed) the sequence will pick of where it left off.

Upvotes: 5

Related Questions