How to pass random number generation function to Python class?

I would like to be able to pass a random number generator to a class in Python. A class is a simulation study, in which a specific set of variables is initialized with the draw of the beta-distribution, which can be created with the help random.betavariate(2,2), but I would like to allow users to connect to the future function of generating random numbers are another type, for example random.uniform(0,1).

When I try to initialize it like this ...

class simulation:
  def __init__(self,rng):
    self._rng = rng

s = simulation(random.betavariate(2,2))

... the error is that instead of passing the function itself, I only pass a freshly generated random number.

>>> s._rng
0.5013004813544717
>>> s._rng
0.5013004813544717

: , , ? , , (re) random.

+4
3

partial functools , , .

>>> from functools import partial
>>> import random
>>> r = partial(random.betavariate, 2, 2)
>>> r()
0.7961360011285323
>>> r()
0.15143718490838257
+8

random.betavariate. random.betavariate(2, 2), . () simulation.

, :

s = simulation(random.betavariate)

, ( , , ).

, , :

s = simulation(lambda: random.betavariate(2, 2))

, random.betavariate(2, 2).

+4

Maybe a closure?

>>> class simulation(object):
...     def __init__(self, rng):
...         self.rng = rng
... 
>>> def f(func, *args):
...     def ret():
...         return func(*args)
...     return ret
...
>>> bar = f(random.randint, 0, 9)
>>> s = simulation(bar)
>>> s.rng()
6
>>> s.rng()
3
>>> s.rng()
9
>>> s.rng()
1
>>> 

Although partialout functoolsseems more natural.

0
source

All Articles