提问者:小点点

Django运行时错误:在__init__中调用方法导致超过最大递归深度


我想调用password_generator方法时注册类被实例化,并分配值返回从方法到密码字段。

当寄存器对象被实例化时,为什么我得到

/register运行时错误

调用Python对象时超过最大递归深度

这是密码

models.py

class Register(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    email = models.EmailField(max_length=120, blank=False, null=False)
    password = models.TextField(blank=False, null=False)
    firstname= models.CharField(max_length=120, blank=False, null=False)
    lastname = models.CharField(max_length=120, blank=False, null=False)
    phonenumber = models.CharField(max_length=120, blank=True, null=True)

    def __init__(self, *args, **kwargs):
        self.password = Register().password_generator()

    #Generate random login password for candidate
    def password_generator(self, size=30, chars=string.ascii_letters + string.digits + string.punctuation):
        return ''.join(random.choice(chars) for i in range(size))

来自终端的日志

控制台

  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()
  File "D:\Project\Online-Examination-System\register\models.py", line 31, in __init__
    self.password = Register().password_generator()

如何解决这个问题?


共1个答案

匿名用户

经过多次尝试,我意识到我试图调用的函数处于无限循环中。要访问password_generator()方法,我必须执行寄存器()。password_generator()。所以这也意味着__init__方法被调用-因为寄存器()。在__init()__中,我再次调用寄存器()。这就是为什么它变成了一个无限循环。为了解决这个问题,我们必须使用:

    def __init__(self, *args, **kwargs):
    self.password = self.password_generator()