简体   繁体   English

Python function 调用 class

[英]Python function call in class

I would like to make a class that returns a pseudo random number generator.我想做一个返回伪随机数生成器的 class 。 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'".我想将 _rand function 的结果保存在 _r 中,但是当我调用 function _rand(int(time.time())) 时,我收到错误消息“rand() 缺少 1 个必需的位置参数:'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; _rand()取两个 arguments; self and seed . selfseed Specifically you need to provide what instance the method is being called on.具体来说,您需要提供正在调用该方法的实例。 Instead of what you have, try defining _r in a constructor而不是你所拥有的,尝试在构造函数中定义_r

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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