gpt4 book ai didi

python - 每当我进行 OOP 时,“超出最大递归深度”

转载 作者:行者123 更新时间:2023-11-28 20:45:50 26 4
gpt4 key购买 nike

  File "C:\tv.py", line 20, in set_channel
self.channel = new_channel
RuntimeError: maximum recursion depth exceeded

我正在尝试我的第一个 OOP 问题。我的课本中的问题是:

“编写一个程序,通过将电视创建为对象来模拟电视。允许用户增大/减小音量,并设置 channel 号。确保 channel 和音量值保持在有效范围内。 "

我的问题是:

  1. 我的结构大致正确吗? (因为我选择了为 inc/dec volume 等制作方法)

  2. 为什么会出现递归错误?我想这意味着我处于某种无限循环中,但我绝对看不到它。

我未完成的“解决方案”:

# Television with Classes
# User able to enter a channel number
# and increase/decrease the volume

class Television(object):
"""A TV set."""
def __init__(self, channel = 1, volume = 20):
self.channel = channel
self.volume = volume

def get_channel(self):
"""Return current channel."""
return self.channel

def set_channel(self, new_channel):
"""Set the channel."""
if 1 < new_channel > 5:
print "Invalid Channel. Must be between 1-5."
else:
self.channel = new_channel

channel = property(get_channel, set_channel)

def show_volume(self):
"""Return current volume."""
return self.volume

def inc_volume(self):
"""Increase the volume by 1 unit."""
if self.volume >= 20:
print "Volume is at maximum: ", get_volume, "\n"
else:
self.volume += 1

def dec_volume(self):
"""Decrease the volume by 1 unit."""
if self.volume <= 0:
print "Volume is at minimum: ", get_volume, "\n"
else:
self.volume -= 1


sony = Television()
print "Current channel: ", sony.channel
print "Changing channel to 3..."
sony.channel(3)
print "Current channel: ", sony.channel
print "Current volume: ", self.volume
print "Increasing volume..."
sony.inc_volume()
print "Current volume: ", self.volume

raw_input("\n\nPress enter to exit.")

最佳答案

您的属性与您尝试使用该属性访问的值同名。因此,当您访问它时,它会递归地尝试获取它自己的值(value)。

重命名属性应该可以解决它。

将代码改成这样:

channel = 0
Channel = property(get_channel, set_channel)

将阻止递归的发生。您将拥有 Channel 作为属性(如此称呼),它使用 get/set_channel 方法访问 channel 字段。

对此属性的分配也不适用于 sony.channel(3)。您必须像任何其他值一样实际分配给该属性:

sony.channel = 3

或者(如果你已经改变了属性问题)

sony.Channel = 3

不过,这不会阻止您以后遇到的卷问题。 self.volume 未声明为字段(或相关属性),inc/dec_volume 函数中的 get_volume 也是如此。

关于python - 每当我进行 OOP 时,“超出最大递归深度”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22249961/

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