在另一个python文件中使用函数内部的变量 [英] Using variables inside a function in another python file

查看:798
本文介绍了在另一个python文件中使用函数内部的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法做到这一点。

i cant seem to make this work.

我有2个python文件,比方说a.py和b.py

I have 2 python files, lets say a.py and b.py

是:

def foo():
    global name
    name = "foo"
    import b
    b.bar()

if __name__ == "__main__":
    foo()

在b.py中:

import a

def bar():
    name = a.name
    print(name)

我对此代码有三个不同的问题:

I have three different question in relation to this code:


  1. 为什么我会收到错误: AttributeError:'module'对象没有属性'name'
    我知道肯定b.py无法访问b.py中函数中定义的变量,但我该如何解决这个问题呢?

  2. 在这种情况下全局会改变什么吗?如果没有,为什么?

  3. 我尝试做 name = a.foo.name 而不是 name = a .name 但是这并没有做到这一点并给我: AttributeError:'function'对象没有属性'name'
    这在任何情况下都是切实可行的,我做错了什么?

  1. Why do i get the error: AttributeError: 'module' object has no attribute 'name' I know for certain that b.py cant access the variable defined in the function in b.py but how do i solve this?
  2. does global in this case changes anything? if not, why?
  3. i tried doing name = a.foo.name instead of name = a.name but this doesnt do the trick either and gives me: AttributeError: 'function' object has no attribute 'name', is this even practicable in any case and what did i do wrong?

感谢您花时间和对不起,如果这对某些人来说显而易见你还在考虑这个问题。

Thanks for taking the time and sorry if this seems obvious to some of you, i'am still getting into this.

推荐答案

脚本不是模块。这是一个令人头疼的东西,但是当你运行 python3 a.py 时, a.py 不是一个模块(或者更确切地说,它是一个名为 __ main __ 的模块,并在导入时重新加载。

Scripts aren't modules. Its something of a mind bender but when you run python3 a.py, a.py isn't a module (or more properly, its a module named __main__) and it will be reloaded when you import.

假设我有 c.py

print('hello')
if __name__=="__main__":
    import c

当我运行它时我得到了

hello
hello

用你的例子说明,如果我将 b.py 更改为

To illustrate with your example, if I change b.py to

import __main__

def bar():
    name = __main__.name
    print(name)

它有效。但只是因为如果有人导入 a 你仍然有两个模块和两个变量副本。

It works. But only kindof because if somebody imports a you've still got two modules and two copies of the variable.

如果您需要共享数据,则必须使用导入的模块,而不是顶级脚本。当我想要共享数据时,我创建了一个单独的模块,它不会导入任何东西(或只导入标准库),它是空的或者我想要共享的变量有默认值。

If you want shared data, they have to be in imported modules, not top level scripts. When I want shared data, I create a separate module that doesn't import anything (or only imports from the standard library) and it is either empty or has defaults for the variables I want to share.

这篇关于在另一个python文件中使用函数内部的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆