我创建了一个类似于电视及其遥控器的程序。但是当我运行代码并尝试打开电视作为第一选择时,它会显示“AttributeError:无法设置属性”。这是代码:
class Television(object):
"""A TV."""
def __init__(self, channel=1, volume=10):
self.channel=channel
self.volume=volume
def __str__(self):
data="\nChannel : "+str(self.channel)+"\nVolume : "+str(self.volume)
return data
def __set_channel(self, channel):
if channel==self.channel:
print("\nYou are already watching channel ", channel)
else:
self.channel=channel
print("\nYou are now watching channel ", channel)
channel=property(__set_channel)
def __set_volume(self, volume):
self.volume=volume
print("\nYour current volume is ", volume)
volume=property(__set_volume)
class Remote(object):
"""A remote control for the TV."""
def __get_channel(self):
channel=input("\nEnter the channel number : ", channel)
if not channel:
print("\nYou have to enter a channel number.")
else:
try:
int(channel)
except(ValueError):
print("\n", channel, " is not a valid channel.")
else:
if channel not in range(1, 101):
print("\n", channel, " is not in range.")
else:
return channel
channel=property(__get_channel)
def __volume_up(self, volume):
volume+=1
if volume>100:
print("\nYou are currently at maximum volume.")
else:
return volume
def __volume_down(self, volume):
volume-=1
if volume<0:
print("\nYou are currently at maximum volume.")
else:
return volume
class OFF(object):
"""A TV at off state."""
def get_choice(state):
"""Gets a choice from the user."""
if state==0:
print(\
"""
MUATHASIM TV
0 - Quit
1 - Switch the TV on
""")
else:
print(\
"""
MUATHASIM TV
0 - Quit
1 - Switch off the TV
2 - Change the channel
3 - Turn up the volume
4 - Turn down the volume
""")
choice=input("\nChoice : ")
return choice
def main():
"""Main part of the program."""
remote=Remote()
choice=None
state=0
while choice!="0":
choice=get_choice(state)
if state==0:
if choice=="0":
print("\nGood Bye!")
elif choice=="1":
TV=Television()
else:
print("\n", choice, " is not a valid choice.")
elif state==1:
if choice=="0":
print("\nGood Bye!")
elif choice=="1":
TV=OFF()
elif choice=="2":
channel=remote.channel
TV.channel=channel
elif choice=="3":
volume=remote.__volume_up(TV.volume)
TV.volume=volume
elif choice=="4":
volume=remote.__volume_down(TV.volume)
TV.volume=volume
else:
print("\n", choice, "is not a valid choice.")
main()
input("\n\n\nPress the Enter key to exit.")
答案 0 :(得分:5)
问题在于您创建属性的方式:
channel=property(__set_channel)
使用 getter函数 __set_channel
创建一个属性。
您必须创建适当的getter函数,例如:
def __get_channel(self):
return self._channel
并将该属性创建为
channel = property(__get_channel, __set_channel)
最后,您需要修复您的setter函数:self.channel = channel
将调用setter函数,从而导致无限循环。请改用self._channel = channel
。