如何从另一个文件调用python类函数

时间:2011-07-15 14:00:15

标签: python

我的parser.py文件中有这个类

class HostInfo(object):
def __init__(self, host_id):
    self.osclass = []
    self.osmatch = []
    self.osfingerprint = []
    self.portused = []
    self.ports = []
    self.extraports = []
    self.tcpsequence = {}
    self.hostnames = []
    self.tcptssequence = {}
    self.ipidsequence = {}
    self.trace = {'port': '', 'proto': '', 'hop': []}
    self.status = {}
    self.address = []
    self.hostscript = []

    # Umit extension
    self.id = host_id
    self.comment = ''

    # XXX this structure it not being used yet.
    self.nmap_host = {
            'status': {'state': '', 'reason': ''},
            'smurf': {'responses': ''},
            'times': {'to': '', 'srtt': '', 'rttvar': ''},
            'hostscript': [],
            'distance': {'value': ''},
            'trace': {'port': '', 'proto': '', 'hop': []},
            'address': [],
            'hostnames': [],
            'ports': [],
            'uptime': {'seconds': '', 'lastboot': ''},
            'tcpsequence': {'index': '', 'values': '', 'class': ''},
            'tcptssequence': {'values': '', 'class': ''},
            'ipidsequence': {'values': '', 'class': ''},
            'os': {}
            }

之后,它定义了一个试图从xml文件中找到主机ID的函数

def get_id(self):
    try:
        return self._id
    except AttributeError:
        raise Exception("Id is not set yet.")

def set_id(self, host_id):
    try:
        self._id = int(host_id)
    except (TypeError, ValueError):
        raise Exception("Invalid id! It must represent an integer, "
                "received %r" % host_id)

现在我想使用另一个文件调用此get_id函数。我尝试了很多时间,但它显示错误,即模块无法导入

1 个答案:

答案 0 :(得分:10)

from parser import HostInfo

obj = HostInfo(<whatever host_id you need here>)
obj.get_id

这就是方法,你是怎么做到的?