首页 > 解决方案 > __init__() 缺少 1 个必需的位置参数:'rec'

问题描述

我是 python 新手。我试图调用一个类的构造函数,但它给了我以下错误:

TypeError:init()缺少1个必需的位置参数:'rec'

我对下面的listen()有同样的问题。请丢弃rms()andrecord()因为它们是其他功能这是我的代码:

class Recorder:

    def __init__(rec):
        rec.p= pyaudio.PyAudio()
        rec.stream= rec.p.open(format=FORMAT, channels=CHANNELS, rate=RATE,input=True,output=True,frames_per_buffer=chunk)


    # listen to the sound
    def listen(rec):
        print('Listening beginning')
        while True:
            input = rec.stream.read(chunk, execption_on_overflow=False)
            rms_val = rec.rms(input)
            if rms_val > Threshold:
                rec.record()

k = Recorder()
k.listen()

标签: python

解决方案


嗯,我无法重现该错误。我只关注__init__方法,因为那是你的关键部分。

测试.py

import pyaudio

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"

class Recorder:
    def __init__(rec):
        rec.p = pyaudio.PyAudio()
        rec.stream = rec.p.open(format = FORMAT, channels = CHANNELS, rate = RATE, input = True, output = True, frames_per_buffer = CHUNK)

    # listen to the sound
    def listen(rec):
        print('Listening beginning')

if(__name__ == "__main__"):
    k = Recorder()
    k.listen()

>> python Test.py
>> Listening beginning

我的设置

Python 3.6.8 (tags/v3.6.8:3c6b436a57, Dec 24 2018, 00:16:47) [MSC v.1916 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

>>> import pyaudio
>>> print(pyaudio.__version__)
0.2.11

因此,请指定您的版本并提供有关您的问题的一些附加信息。

我假设您使用像这样的构造函数

def __init__(self, rec):
   ...

但是您没有将任何参数传递给rec. 这将解释您的错误:

Traceback (most recent call last):
  File ".../Test.py", line 20, in <module>
    k = Recorder()
TypeError: __init__() missing 1 required positional argument: 'rec'

推荐阅读