gpt4 book ai didi

python - 如何修复 __str__ 方法产生的无限循环?

转载 作者:太空宇宙 更新时间:2023-11-04 08:34:07 25 4
gpt4 key购买 nike

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: maximum recursion depth exceeded”

我不太确定为什么会这样。

这是导致问题的代码:

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.nameself .long_desc - 即问题发生的时间。

总的来说这是一团糟,但我真的想在继续之前弄清楚这一点。奇怪的是它只发生在 Trait 而不是子类 AreaOfEffect__str__

最佳答案

你需要改变:

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

收件人:

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

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

关于python - 如何修复 __str__ 方法产生的无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50574241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com