Python 2.7-类 [英] Python 2.7 - Classes

查看:96
本文介绍了Python 2.7-类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在python (perfmon)中编辑库-文件为session.py

I'm trying to edit a library in python (perfmon) - the file is session.py

我想添加一个模块,该模块可以记录来自USB端口的一些读数.

I want to add a module that can record some readings from a USB port.

这也是我第一次使用python类进行试用

This is also my first trial with classes in 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

这是我收到的以下错误:

This is the following error I am getting:

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中充当构造函数,我可以在其中返回值吗?

What is the mistake I am doing? I understood that self acts as a constructor in python, Can I return a value there?

推荐答案

据我了解,在您的情况下,答案是

as I understand in Your case answer is

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

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

But this way You move is wrong. You should create your own module in your workspace/project dir. Import session module and Create class there

from perfmon import session
class USB(Session):
    def __init__(self):   
        pass #I have changed this part as It has two errors in your example

这篇关于Python 2.7-类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆