无法构造python类

时间:2018-08-07 15:01:07

标签: python

我具有以下功能,这些功能在Python脚本的边界内起作用

loop_vcenters函数将返回字典,而cluster: host subs_per_socket函数将返回esx的套接字数

def loop_vcenters(vcenters):
    #------------------------- connect to vcenter ----------------------------------------
    si = SmartConnect(host = vcenters,user = 'username',pwd = 'password' ,sslContext=context)
    # disconnect from vcenter one done
    atexit.register(Disconnect, si)
    #get the object content from vcenter
    content = si.RetrieveContent()
    #list clusters
    cluster_host_dic_list=[]
    cluster_name = ""
    for cluster_obj in get_obj(content, vim.ComputeResource):
        cluster=cluster_obj.name
        hosts=[]
        for host in cluster_obj.host:
            hosts.append(host.name)
        #create dictinary ,key=cluster value=esx
        cluster_dic={cluster:hosts}
        cluster_host_dic_list.append(cluster_dic)
    return cluster_host_dic_list

def subs_per_socket(host):
    shost = content.searchIndex.FindByDnsName(dnsName=host, vmSearch=False)
    socket_count = shost.summary.hardware.numCpuPkgs
    sub_per_socket = socket_count/2
    return sub_per_socket

我想将两个函数都放在一个类中,但是我不知道怎么做

class loop_vcenters:    
    def hosts_dic(self,name):
        si = SmartConnect(host = vcenters,user = 'username',pwd = 'password' ,sslContext=context)
        atexit.register(Disconnect, si)
        content = si.RetrieveContent()
        cluster_host_dic_list=[]
        cluster_name = ""
        for cluster_obj in get_obj(content, vim.ComputeResource):
            cluster=cluster_obj.name
            hosts=[]
            for host in cluster_obj.host:
                hosts.append(host.name)
            cluster_dic={cluster:hosts}
            cluster_host_dic_list.append(cluster_dic)
      return cluster_host_dic_list
  1. 我无法像返回的loop_vcenters函数那样获得宿主词典。
d = loop_vcenters('vcenters')
Traceback (most recent call last):
File "", line 1, in 
  File "", line 5, in __init__
NameError: global name 'vcenters' is not defined
  1. 如何将subs_per_socket(host)函数添加到类中?

1 个答案:

答案 0 :(得分:0)

d = loop_vcenters('vcenters')

在未定义 init 的情况下,您正在使用参数调用类loop_vcenters。

文件“”,第5行,在 __ init __

NameError:全局名称'vcenters'未定义

如果要将参数传递给host_dic,则应该调用

d = loop_vcenters.host_dic('vcenters')

这将把cluster_host_dic_list返回到变量d。

要添加subs_per_socket(host),只需在类下定义它,就像执行其他功能一样。