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

标签 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 函数。我试了很多次但它显示错误,即模块无法导入

最佳答案

from parser import HostInfo

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

原来是这样,你是怎么做到的?

关于python - 如何从另一个文件调用python类函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6708125/

相关文章:

python - 在页面上使用 selenium 查找电子邮件地址

python - 重定义对象的方法

python - 正常的Python代码和多处理中的相同代码之间的时间差是多少?

python - 计算 DataFrame 中每一列的第一个非缺失值

Python:生成具有趋势的随机时间序列数据(例如周期性、指数衰减等)

Python Tkinter 笔记本小部件

python - Altair 中的多列/行小平面环绕

python - 我如何找到与给定主机的连接将通过哪个接口(interface)路由?

python - 在VS Code API中,如何获取Python环境路径?

python - PyQt5 不同选项卡上的不同网格