【问题标题】:Classes and methods in Python (methods and attributes separated by definitions)Python 中的类和方法(由定义分隔的方法和属性)
【发布时间】:2014-12-11 14:56:50
【问题描述】:

代码有什么问题?

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 可以正常工作。

提前致谢。

【问题讨论】:

    标签: python class methods attributes initialization


    【解决方案1】:

    数据属性和方法共享相同的命名空间。你需要给它们起不同的名字。

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

    【讨论】:

      【解决方案2】:

      您正在调用您的记录器函数,而不是记录器函数输出..并且您的记录器函数没有 start_stream() 方法..

      试试这个:

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

      【讨论】:

      • 或者简单地说:self.recorder().start_stream()
      猜你喜欢
      • 1970-01-01
      • 2017-06-10
      • 2014-11-06
      • 2017-03-13
      • 1970-01-01
      • 1970-01-01
      • 2010-10-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多