交叉模块变量 [英] cross module variable

查看:140
本文介绍了交叉模块变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自此处来自其他模块的变量.一切都很好

from here I got an idea about how using variables from other modules. this all works fine with

import foo as bar

但是我不想将模块导入为"bar",我想不带任何前缀使用它,例如

But I don't want to import my modules as "bar" I want to use it without any prefix like

from foo import *

使用此方法,无法修改其他模块中的变量.阅读会起作用!任何的想法?有什么建议吗?

Using this it´s impossible to modify variables from other modules. reading will work! any idea? suggestions?

推荐答案

据我所知,没有办法从模块中导入值 并使其在导入时可读写范围.当您在Python中只是import foo时,它将创建一个名为foo的模块对象.在模块对象上获取和设置属性将在模块范围内更改它们.但是,当您from foo import something时,将导入foo并创建一个模块对象,但不会返回.取而代之的是,Python从foo中复制您指定的值,并将其放在本地范围内.如果要导入的是诸如intstr之类的不可变类型,则无法对其进行更改并使更改反映在foo模块中.类似于这样:

As far as I know, there is no way to import a value from a module and have it readable and writable by the importing scope. When you just import foo in Python, it creates a module object named foo. Getting and setting attributes on a module object will change them in the module's scope. But when you from foo import something, foo is imported and a module object is created, but is not returned. Instead, Python copies the values you specified out of foo and puts them in the local scope. If what you are importing is an immutable type like int or str, then changing it and having the changes reflect in the foo module is impossible. It's similar to this:

>>> class N(object):
...   def __init__(self, value):
...     self.value = value
>>> n = N(3)
>>> value = n.value
>>> print value, n.value
3 3
>>> value = 4
>>> print value, n.value
4 3

除了粗暴的黑客攻击外,如果您确实希望能够修改模块的变量,则需要导入模块本身并修改模块上的变量.但是通常,必须这样做表明设计不良.如果您是有问题的foo模块的编写者,则可能希望查看其他一些更Python化的方法来解决问题.

Excepting crude hacks, if you really want to be able to modify the module's variable, you will need to import the module itself and modify the variable on the module. But generally, having to do this is indicative of bad design. If you are the writer of the foo module in question, you may want to look at some other, more Pythonic ways to solve your problem.

这篇关于交叉模块变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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