我需要制作一个向用户显示频道和音量的电视,并显示电视是否打开.我有大部分代码,但由于某种原因,频道不会切换.我对属性的工作方式还不太熟悉,我认为这就是我的问题所在.请帮忙.
class Television(object):
def __init__(self, __channel=1, volume=1, is_on=0):
self.__channel=__channel
self.volume=volume
self.is_on=is_on
def __str__(self):
if self.is_on==1:
print "The tv is on"
print self.__channel
print self.volume
else:
print "The television is off."
def toggle_power(self):
if self.is_on==1:
self.is_on=0
return self.is_on
if self.is_on==0:
self.is_on=1
return self.is_on
def get_channel(self):
return channel
def set_channel(self, choice):
if self.is_on==1:
if choice>=0 and choice<=499:
channel=self.__channel
else:
print "Invalid channel!"
else:
print "The television isn't on!"
channel=property(get_channel, set_channel)
def raise_volume(self, up=1):
if self.is_on==1:
self.volume+=up
if self.volume>=10:
self.volume=10
print "Max volume!" …Run Code Online (Sandbox Code Playgroud) 我正在制作一个你正在发射"爆炸"的程序,我有5个弹药.我正在爆炸一个有5个健康的外星人.最后,我实例化播放器并让他爆炸6次以检查程序是否正常工作.但是我这样做的方式使得数量不会减少.有没有一个简单的解决方案,或者我只需要为弹药和健康创建一个新的属性?这就是我所拥有的:
class Player(object):
""" A player in a shooter game. """
def blast(self, enemy, ammo=5):
if ammo>=1:
ammo-=1
print "You have blasted the alien."
print "You have", ammo, "ammunition left."
enemy.die(5)
else:
print "You are out of ammunition!"
class Alien(object):
""" An alien in a shooter game. """
def die(self, health=5):
if health>=1:
health-=1
print "The alien is wounded. He now has", health, "health left."
elif health==0:
health-=1
print "The alien gasps and says, 'Oh, this is it. This is …Run Code Online (Sandbox Code Playgroud)