【发布时间】:2020-01-10 04:06:57
【问题描述】:
我尝试更改一个类变量,但更改对在另一个模块初始化的该类的实例无效
包结构为:
├── 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)
在 pclab/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
【问题讨论】:
-
你能把你的代码转成minimal reproducible example吗?实际上,无法运行它并重现您的问题。例如,您的代码尝试在
StemBase中打印一个来自无处的stem_cls,这让我认为您在此处简化的示例与您的代码的真实结构并不真正匹配。 -
StemBase 中的 stem_cls 是复制/过去的错字:stem_cls -> self.我已经更新了这个问题。感谢您指出。是的,我会尽量减少代码,但这需要我一段时间
-
能不能把这段代码之外的函数和类的引用去掉,直接执行?这就是minimal reproducible example 的想法。
-
删除对
common.scene.SceneObject的引用后,代码按预期工作,最后一次打印时给出了`StemBase.__init__ self.MIN_NUM_KNEES: 3`。您的原始代码中还有其他内容您没有在此处重现。
标签: python python-module