简体   繁体   English

从包中导入时重置类属性

[英]Class attributes reset when imported from package

I have a project that is organized something like 我有一个类似这样的项目

project/
    __init__.py
    builder.py
    component/
        __init__.py

Within builder.py , I have a class called Builder that has several class attributes in order to implement the Borg pattern. builder.py ,我有一个名为Builder的类,该类具有几个类属性以实现Borg模式。 The trouble arises when I try to import Builder in component/__init__.py and make changes to class attributes. 当我尝试在component/__init__.py导入Builder并更改类属性时,就会出现问题。 It seems that whatever changes I make to the class attributes in the package are undone when the function returns. 似乎我对该程序包中的类属性所做的任何更改在该函数返回时都被撤消。

UPDATE: Here is a simple example of what is happening. 更新:这是正在发生的事情的一个简单示例。

builder.py builder.py

class Builder(object):
    attribute = True

import component

print Builder.attribute

component/___init___.py 组件/___init___.py

from project.builder import Builder

Builder.attribute = False

Output: 输出:

False
True

Judging by the fact that two lines are printed, I would guess that the code in builder.py is being executed twice, which resets the value of attribute to True. 从打印两行的事实来看,我猜想builder.py中的代码执行了两次,这会将attribute的值重置为True。

What you have is a circular import: builder imports component, component imports builder. 您拥有的是循环导入:构建器导入组件,组件导入构建器。

At the time builder imports component, builder is not yet fully constructed. 在构建器导入组件时,构建器尚未完全构建。 Then component imports builder, which executes the rest of builder module (all after import component ). 然后,组件导入构建器,该构建器执行构建器模块的其余部分(全部在import component )。 Later, when component is loaded, builder continues again with everything after import component . 稍后,在加载组件时,构建器将继续执行import component之后的所有import component

Note that the behaviour would be different if component was loaded first! 请注意,如果首先加载组件,则行为会有所不同!

Basically, you should not do circular imports. 基本上,您不应该进行循环导入。 Try to organise the code in some other way. 尝试以其他方式组织代码。

You should really show (a simplified version of) your code. 您应该真正显示您的代码(简化版)。 Something like (assuming eg that project is in sys.path): 诸如此类(假设该project位于sys.path中):

import builder
builder.Builder.baah = 'boo!'

in component/__init__.py , for example, should work just fine with no "undoing" nor "resetting". 例如,在component/__init__.py应该没有“撤消”或“重置”即可正常工作。

But what code exactly are you using instead, to perform those "whatever changes"...? 但是,什么样的代码你到底不是使用,执行那些“什么变化” ......?

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

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