0

我正在尝试在 python 中编辑一个库(perfmon)- 该文件是session.py

我想添加一个可以从 USB 端口记录一些读数的模块。

这也是我第一次尝试使用 python 中的类

from perfmon import *
import os
import sys
import serial

# Common base class
class Session:
  def __init__(self, events):
    self.system = System()
    self.event_names = events
    self.events = []
    self.fds = []
    for e in events:
      err, encoding = pfm_get_perf_event_encoding(e, PFM_PLM0 | PFM_PLM3,
                                                  None, None)
      self.events.append(encoding)
    self.USB = serial.Serial("/dev/ttyUSB0",115200)

  def __del__(self):
    pass

  def read(self, fd):
    # TODO: determine counter width
    return os.read(fd, 8)

class PerThreadSession(Session):
  def __init__(self, pid, events):
    self.pid = pid
    Session.__init__(self, events)

  def __del__(self):
    Session.__del__(self)

  def start(self):
    for e in self.events:
      self.fds.append(perf_event_open(e, self.pid, -1, -1, 0))

  def read(self, i):
    return Session.read(self, self.fds[i])

class USB(Session):
  def __init__(self):   
    return self.USB

这是我得到的以下错误:

Python 2.7.3 (default, Apr 14 2012, 08:58:41) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import perfmon
>>> test = perfmon.USB()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'USB'

我在做什么错误?我知道 self 在 python 中充当构造函数,我可以在那里返回一个值吗?

4

2 回答 2

2

不能从类构造函数返回任何内容(除了无)。

否则会得到

TypeError: __init__() should return None
于 2013-06-13T19:38:53.340 回答
1

正如我在你的案例中所理解的那样,答案是

>>> from perfmon import session
>>> test = session.USB()

但是这种方式你移动是错误的。您应该在工作区/项目目录中创建自己的模块。导入会话模块并在那里创建类

from perfmon import session
class USB(Session):
    def __init__(self):   
        pass #I have changed this part as It has two errors in your example
于 2013-06-13T19:38:58.787 回答