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

时间:2014-12-11 14:56:50

标签: 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=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正常工作。

提前致谢。

2 个答案:

答案 0 :(得分:0)

数据属性和方法共享相同的名称。你需要为它们命名。

如果要创建属性或引用属性,则需要使用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()
        ...

答案 1 :(得分:0)

您正在调用录音机功能,而不是录音机功能输出..并且您的录音机功能没有start_stream()方法..

试试这个:

def start(self):
    in_speech_bf = True
    rec = self.recorder()
    rec.start_stream()
相关问题