python - 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”。你能帮帮我吗?
解决方案
全局变量是模块的属性,而不是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
全局的任何分配而改变。
推荐阅读
- javascript - 无法区分“相似”代码
- matlab - For 循环似乎比矩阵运算更快
- python - 如何在日期时间解决 Errno 22
- java - 如何在 Java 中生成八位字节字符串?
- ansible - 如何在ansible中一次访问一组主机名?
- markdown - 为什么我在 Jekyll 网站上的 markdown 代码块周围出现双框?
- azure-storage - 如何查找 Azure 驱动器类型?
- javascript - Angular CDK 布局 - 如何在整个项目中全局包含 BreakPointObserver
- python - 如何修复 Python 3.7 中的“KeyError:****_target”错误
- paypal - PayPal 结帐和 Braintree 类的问题