我有一个现成的班级,因此我正在获得一本字典, 如果我将方法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,内容,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
我做错了什么?
答案 0 :(得分:1)
展开我的评论:迷你示例
>>> 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)
答案 1 :(得分:0)
只需添加更多解释并为答案写几个其他选项即可。 //module.py A类: x = 1 此属性是类中的“静态属性”,您可以通过调用A.x引用类外的内容,而无需创建对象。 在添加变量self(self.x)之前需要在方法中添加self之前先添加注释。 还有另一个选择,就是在构造函数中声明属性,例如: def init (自己): self.x =“ 1” 在此选项中,属性是按对象而不是按类。 (因此更改仅适用于当前对象) 如果需要全局变量(在模块文件中),则可以将变量写入模块中,如下所示: //module.py x = 1 A类: ... ... 您可以在任何地方使用此全局变量... pd:如果需要更改值,则需要添加 全局x,其他仅是只读的。