简体   繁体   中英

Python function call in class

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())

_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()))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM