Home > Software engineering >  Python function call in class
Python function call in class

Time:11-30

I would like to make a class that returns a pseudo random number generator. I want to save the result of the _rand function in _r but when I call the function _rand(int(time.time())) I get the error message "rand() missing 1 required positional argument: 'seed'". Could someone please explain me what I did wrong.

class PRNG:
import time
_m = 32768
_b = 9757 
_c = 6925
 
 def _rand(self, seed):
     n = seed % self._m
     while True:
         n = (n * self._b   self._c) % self._m
         yield n

_r = _rand(int(time.time()))
         
 def rand(self) :
     return self._r.__next__() 
        
prng = PRNG()
print(prng.rand())

CodePudding user response:

_rand() takes two arguments; self and seed. Specifically you need to provide what instance the method is being called on. Instead of what you have, try defining _r in a constructor

def __init__(self):
    self._m = 32768
    self._b = 9757 
    self._c = 6925
    self._r = self._rand(int(time.time()))
  • Related