简体   繁体   English

通过导入Python全局变量?

[英]Python Global Variable Through Import?

Is this form of global variable declaration good practice in Python? 这种形式的全局变量声明是Python的良好实践吗? My dictionary has no data in B.py in some cases. 在某些情况下,我的字典在B.py中没有数据。 Just seems inconsistent. 只是看起来不一致。

classes.py classes.py

class Aclass:
    dict = {}

myClass = Aclass()

A.py: A.py:

from classes import myClass

myClass.dict["variable"]

B.py: B.py:

from classes import myClass

print str(myClass.dict)

A.py is processed before B.py. A.py在B.py之前处理。 This prints an empty dict {} for me. 这会为我打印一个空的dict {}

This is a simplified question from previous post: Shared/Global Dictionary in Django Between URLs and Context Processor . 这是前一篇文章中简化的问题: Django中的URL和上下文处理器之间的共享/全局字典 Your insight is appreciated. 非常感谢您的见解。

if in A.py you change it to 如果在A.py中将其更改为

myClass.dict["variable"]="hello"

(as pointed out in comments) (正如评论中所指出)

then the question becomes interesting. 然后问题变得有趣。

it's ok but it's better to have another interface (functions, methods) to that data. 没关系,但最好有另一个接口(函数,方法)来处理这些数据。 It's a way to store a state of the module. 这是一种存储模块状态的方法。 The object you called myClass (!) is the same both from a and b. 您调用myClass(!)的对象与a和b相同。

multiple imports are safe and do nothing except to return the same loaded module. 多个导入是安全的,除了返回相同的已加载模块外什么也不做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM