首页 > 解决方案 > AttributeError:“函数”对象没有属性

问题描述

我需要访问全局变量(g)。它存在于类内的另一个 python 文件中。请建议我如何访问。

测试1.py:

class cls():
    def m1(self):
       inVar = 'inside_method'
       global g
       g = "Global"
       x = 10
       y = 20
       print("Inside_method", inVar)
       print (x)
       print (y)
       print (g)
obj = cls()
obj.m1()

测试2.py:

from test1 import *
print (cls.m1) # I can access all variables in method
print (cls.m1.g) # getting error while accessing variable inside the function

我希望从我的 test2.py 中访问变量“g”。你能帮帮我吗?

标签: python

解决方案


全局变量是模块的属性,而不是c1类或m1方法。因此,如果您导入了模块而不是模块中的所有名称,则可以在那里访问它:

import test1

# references the `m1` attribute of the `cls` name in he `test1` module
# global namespace.
print(test1.cls.m1)
# references the `g` name in he `test1` module global namespace.
print(test1.g)

您还可以cls().m1()在模块的顶层运行表达式test1,因此在第一次导入任何内容时都会执行它test1。这意味着您的from test1 import *表达式g也在您的test2命名空间中创建了一个名称:

from test1 import *  # imported cls, obj and g

print(g)  # "Global"

但是,该引用不会随着对test1.g全局的任何分配而改变。


推荐阅读