如何从__str__方法修复无限循环生成?

时间:2018-05-28 22:49:51

标签: python loops oop recursion

File "C:\Users\kevin\Documents\Programs\ParLumen\trait.py", line 76, in __str__
    ret_str = super().__str__()
  File "C:\Users\kevin\Documents\Programs\ParLumen\trait.py", line 39, in __str__
    ret_str += f'{self.name}\n'
RecursionError: maximum recursion depth exceeded

这有很多很多行,但它只是重复相同的两行,然后最后的不同行是“RecursionError:超出最大递归深度”

我不确定为什么会这样。

以下是导致此问题的代码:

from abc import ABC, abstractmethod
from enum import Enum, unique

from parlumen.game import *

# Base Trait class
class Trait(ABC):

    def __init__(self, name, short_desc="No Desc", long_desc=None):
        self.name = name
        # self.value = value # may restrict this with req. 'avail_values()' func

        """
        if short_desc is not "No Desc":
            self.short_desc = short_desc
        """
        self.short_desc = short_desc

        if long_desc is None:
            self.long_desc = self.short_desc
        else:
            self.long_desc = long_desc

    @abstractmethod
    def __str__(self):
        ret_str = ""

        ret_str += f'{self.name}\n'
        ret_str += f'{self.long_desc}'

        return ret_str



# Area of Effect Definition

@unique
class Focus(Enum):
    NoFocus  = 'None'
    Origin   = 'Origin'
    Reversed = 'Reversed'

class AreaOfEffect(Trait):

    def __init__(self, area, focus=None):
        super().__init__(self, "Area of Effect")

        self.area = area

        if focus is None :
            self.focus = Focus.NoFocus
        else:
            self.focus = focus

        self.long_desc = f"Gives an attack or spell an area of effect of self.area"

    def __str__(self):
        ret_str = super().__str__()

        ret_str += f"\nArea of Effect: {self.area}, Focus: {self.focus}"

        return ret_str

aoe = AreaOfEffect(3, Focus.Origin)

print(aoe)

更具体地说,问题似乎与__str__ Trait self.name似乎不喜欢self.long_descAreaOfEffect的方法有关 - 这就是问题发生的时间。< / p>

总的来说这有点混乱,但我真的想在继续之前搞清楚这​​一点。奇怪的是它只发生在Trait而不是子类__str__的{​​{1}}

1 个答案:

答案 0 :(得分:5)

您需要更改:

super().__init__(self, "Area of Effect")

要:

super().__init__("Area of Effect")

您正在将name设置为对象实例,然后在尝试格式化str时递归调用name