python中定义变量的TypeError
我正在尝试制作一个音乐播放器,允许将一首歌曲放入外壳中,然后播放。但是,我遇到了一个问题,在python中定义变量的TypeError,python,typeerror,Python,Typeerror,我正在尝试制作一个音乐播放器,允许将一首歌曲放入外壳中,然后播放。但是,我遇到了一个问题,在class Notes():中出现了一个类型错误,我不知道为什么 import winsound import time length = 125 class Notes(): def processNote(note): if(note == 'C'):return Notes.processNote(262) if(note == 'D'):return N
class Notes():
中出现了一个类型错误,我不知道为什么
import winsound
import time
length = 125
class Notes():
def processNote(note):
if(note == 'C'):return Notes.processNote(262)
if(note == 'D'):return Notes.processNote(294)
if(note == 'D5'):return Notes.processNote(587)
if(note == 'A'):return Notes.processNote(440)
if(note == 'Ab'):return Notes.processNote(415)
if(note == 'G'):return Notes.processNote(392)
if(note == 'F'):return Notes.processNote(349)
if(note == 'B'):return Notes.processNote(247)
if(note == 'Bb'):return Notes.processNote(233)
song = "CCCCCCCCCCCD"
noteList = list(song)
print(noteList)
for note in noteList:
print("Doing ", note)
frequency = Notes.processNote(note)
winsound.Beep(frequency, length)
错误:
Traceback (most recent call last):
File "C:\Python\Tester.py", line 27, in <module>
winsound.Beep(frequency, length)
TypeError: an integer is required (got type NoneType)
回溯(最近一次呼叫最后一次):
文件“C:\Python\Tester.py”,第27行,在
winsound.Beep(频率、长度)
TypeError:需要一个整数(获取类型NoneType)
如果我能说点什么,而不是
class Notes():
def processNote(note):
if(note == 'C'):return Notes.processNote(262)
if(note == 'D'):return Notes.processNote(294)
if(note == 'D5'):return Notes.processNote(587)
(thousands IFs)
您可以使用python字典并创建映射:
class Notes():
def processNote(note):
signature_to_freq = {'C': 262, 'D': 294, 'D5': 587,
'B': 247}
return signature_to_freq[note]
目前,函数
processNote()
对于任何有效输入都返回None
,因为您要调用它两次,而不是只返回值。了解代码的处理方式可能有助于理解发生这种情况的原因:
想象一下用注释值调用processNote()
“C”
。它将匹配第一个if
语句,并返回调用processNote()
的结果,其值为262。由于在processNote()
函数中没有捕获262的if语句,因此它返回None
(因为这是Python函数的默认值),因此frequency
变量最终为None
您只需返回文本值,就可以非常简单地解决此问题:
def processNote(note):
if note == 'C':
return 262
...
我相信你的意思是
返回262
等等;当前,您调用函数两次,第二次总是返回None
,因为您传递的是一个整数。您的函数只处理字符串。似乎您的。processNote
方法返回None。噢,我不知道修复方法这么简单谢谢!当然,更改函数的返回也更好(更容易)。编辑。哦,这是一个更整洁的写作方式。我会试着换成谢谢你。