首页 > 解决方案 > python,分配给类变量没有效果

问题描述

我尝试更改一个类变量,但更改对在另一个模块初始化的该类的实例无效

包结构是:

├── pclab  
│   ├── genmgr.py <- StemConfigurator.config_main_stem called here  
...  
├── plant  
│   ├── __init__.py  
...  
│   ├── plants.py <- Stem object created here  
...  
│   └── stem  
...  
│       └── stems.py <- Stem, BaseStem, StemConfigurator defined here  

整个代码由Blender 2.79b内部 python 解释器执行,因此我需要对系统路径做一些 Voodoo。

我有一个实际上看起来像这样的代码:


class StemBase:
    def __init__(self):
        print('StemBase.__init__ object:', self)
        print('StemBase.__init__ self.MIN_NUM_KNEES:', self.MIN_NUM_KNEES)


class Stem(StemBase):
    MIN_NUM_KNEES = 8
    def __init__(self):
        super().__init__()


class StemConfigurator:

    def set_configs(self, stem_cls, configs):
        for k in configs:
            setattr(stem_cls, k, configs[k])
        print('class:', stem_cls)
        print('MIN_NUM_KNEES at set_configs:', stem_cls.MIN_NUM_KNEES)

    def config_main_stem(self, configs):
        self.set_configs(Stem, configs)

在 plab/genmgr.py:

setm_configurator = StemConfigurator()
configs = {'MIN_NUM_KNEES': 3}
setm_configurator.config_main_stem(configs)

在 plant/plants.py 创建一个“Stem”实例:


import os
import sys

curdir = os.path.dirname(__file__)
if curdir not in sys.path:
    sys.path.append(curdir)
rootdir = os.path.dirname(curdir)
if rootdir not in sys.path:
    sys.path.append(rootdir)

from stem import stems

stem = stems.Stem()

上述代码的输出是:

class: <class 'plant.stem.stems.Stem'>
MIN_NUM_KNEES at set_configs: 3
StemBase.__init__ object: <stem.stems.Stem object at 0x7fb74dc95f28>
StemBase.__init__ self.MIN_NUM_KNEES: 8

whereas I would expect the last line to be: 
StemBase.__init__ self.MIN_NUM_KNEES: 3

标签: pythonpython-module

解决方案


解决方案是在 import 语句中为“stem”模块添加句点:

from .stem import stems #originally is was: from stem import stems

stem = stems.Stem()

也许有人可以解释一下它背后的逻辑?谢谢。


推荐阅读