Python中的类和方法(由定义分隔的方法和属性)

Python中的类和方法(由定义分隔的方法和属性),python,class,methods,attributes,initialization,Python,Class,Methods,Attributes,Initialization,代码有什么问题 from pyaudio import * class sphinx(): def __init__(self, samprate=16000): self.recorder(samprate) def recorder(self, samprate): audio = PyAudio() recorder = audio.open(rate=samprate, channels=1, format=paInt1

代码有什么问题

from pyaudio import *

class sphinx():
    def __init__(self, samprate=16000):
        self.recorder(samprate)

    def recorder(self, samprate):
        audio = PyAudio()
        recorder = audio.open(rate=samprate, channels=1, format=paInt16, input=True, frames_per_buffer=1024)
        return recorder

    def start(self):
        in_speech_bf = True
        self.recorder.start_stream()
        ...

decoder = sphinx()
decoder.start()
Python返回:

Traceback (most recent call last):
    File "decoder.py", line 58, in <module>
        decoder.start()
    File "decoder.py", line 28, in start
        self.recorder.start_stream()
AttributeError: 'function' object has no attribute 'start_stream'
当我不使用类和方法时,PyAudio正常工作


提前感谢。

数据属性和方法共享相同的名称apce。你需要给他们起不同的名字

如果你想做一个属性或者引用这个属性,你需要用self来限定这个属性,否则它就变成了局部变量

from pyaudio import *

class sphinx:

    def __init__(self, samprate=16000):
        self.init(samprate)  # renamed the method

    def init(self, samprate):  # renamed the method
        audio = PyAudio()
        self.recorder = audio.open(rate=samprate, channels=1,  # qualify attribute
                                   format=paInt16, input=True,
                                   frames_per_buffer=1024)
        return self.recorder

    def start(self):
        in_speech_bf = True
        self.recorder.start_stream()
        ...

您正在调用记录器函数,而不是记录器函数输出。。并且您的记录器功能没有“开始\u流”方法

试试这个:

def start(self):
    in_speech_bf = True
    rec = self.recorder()
    rec.start_stream()
或者简单地说:self.recorder.start\u stream