首页 > 解决方案 > 无法设置全局变量是一个类

问题描述

我有一个现有的类,结果我得到一个字典,如果我将方法 loop_vcenters 分配给变量名 d

class vmware:
    def loop_vcenters(self,vcenter_name):
            si = SmartConnect(host = vcenter_name,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

x = vmware()

d = x.loop_vcenters('vcenter_name')

print(d)  #will print the dictionary

我正在尝试移动 si,atexit,content,cluster_host_dic_list,cluster_name

要在 loop_vcenters 函数之外充当类中的全局变量,如下所示:

class vmware:
    vcenters = 'vcenter_name'
    si = SmartConnect(host = vcenter_name,user = 'username',pwd = 'password' ,sslContext=context)
    atexit.register(Disconnect, si)
    content = si.RetrieveContent()
    cluster_host_dic_list=[]
    cluster_name = ""
    def loop_vcenters(self):
            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

现在,当我分配 loop_vcenters 方法时,我得到:

无百日咳

x = vcenter_actions()

d = x.loop_vcenters

print(d)

    <bound method vcenter_actions.loop_vcenters of <__main__.vcenter_actions instance at 0x7fd30ea95098>>

或百日咳

d = x.loop_vcenters()

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in loop_vcenters
NameError: global name 'content' is not defined

我做错了什么?

标签: python

解决方案


扩展我的评论:迷你示例

>>> class x:
...     a = 3
...     def print_a(self):
...             print(a)
...
>>> x().print_a()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in print_a
NameError: global name 'a' is not defined
>>> class x:
...     a = 3
...     def print_a(self):
...             print(self.a)
...
>>> x().print_a()
3

尽管您可能也只想直接由类引用它print(x.a)


推荐阅读