-1
所以這裏是我的代碼AttributeError的: '電視' 對象有沒有屬性 '量'
# Television Remote
class Television(object):
def ___init___(self, channel = 15, volume = 20):
self.channel = channel
self.volume = volume
def channell(self, value):
if value > 20:
print("Max channel is 20")
self.channel = 20
return self.channel
else:
self.channel = value
return self.channel
print("Channel is now ", self.channel)
def volume_increase(self):
if self.volume != 100:
self.volume += 1
return self.volume
else:
return self.volume
def volume_decrease(self):
if self.volume != 0:
self.volume -= 1
return self.volume
else:
return self.volume
def channel_up(self):
if self.channel == 20: # 20 is the maximum channel allowed
self.channel = 1 # so it returns to 1
return self.channel
else:
self.channel += 1
return self.channel
def channel_down(self):
if self.channel == 1:
self.channel = 20
return self.channel
else:
self.channel -= 1
return self.channel
c = Television()
choice = None
while choice != "0":
print(
"""
Television Remote
0 - Quit
1 - Input Channel
2 - Change Channel Up
3 - Change Channel Down
4 - Volume Up
5 - Volume Down
""")
choice = input("Choice: ")
if choice == "0":
print("Good Bye")
elif choice == "1":
value = int(input("What channel? "))
c.channell(value)
print("Turning to Channel ", c.channel)
elif choice == "2":
print("Channel ", c.channel_up())
elif choice == "3":
print("Channel ", c.channel_down())
elif choice == "4":
print(c.volume_increase())
elif choice == "5":
print(c.volume_decrease())
else:
print("Choice ", choice, " isn't a valid choice.")
input("Press enter to exit.")
當我選擇2 - 4,這將輸出:
(AttributeError: 'Television' object has no attribute 'volume',)
我不明白爲什麼但如果我只寫這個代碼
class Television(object):
def __init__(self, channel = 15, volume = 20):
self.channel = channel
self.volume = volume
def volume_increase(self):
if self.volume != 100:
self.volume += 1
return self.volume
else:
return self.volume
c = Television()
choice = None
while choice != "0":
print(
"""
Television Remote
0 - Quit
1 - Input Channel
2 - Change Channel Up
3 - Change Channel Down
4 - Volume Up
5 - Volume Down
""")
choice = input("Choice: ")
if choice == "0":
print("Good Bye")
elif choice == "1":
value = int(input("What channel? "))
c.channell(value)
print("Turning to Channel ", c.channel)
elif choice == "2":
print("Channel ", c.channel_up())
elif choice == "3":
print("Channel ", c.channel_down())
elif choice == "4":
print(c.volume_increase())
elif choice == "5":
print(c.volume_decrease())
else:
print("Choice ", choice, " isn't a valid choice.")
並且只能選擇「4」,代碼工作。有人可以向我解釋爲什麼第一個代碼不起作用,第二個代碼起作用嗎?
如果你不明白我的問題,我會以更詳細的方式向你解釋。
打我給它阿南德,正確:) – nico
糟糕,現在運行正常 -
只有兩個下劃線,而不是三個定義
__init__()
功能。謝謝!說如果你不介意。作爲初學者,我可以問另外一個問題,你在哪裏學Python? –有很多很好的教程,其中一個可以是 - https://docs.python.org/3/tutorial/(Python自己的教程)。 –