python - 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
解决方案
解决方案是在 import 语句中为“stem”模块添加句点:
from .stem import stems #originally is was: from stem import stems
stem = stems.Stem()
也许有人可以解释一下它背后的逻辑?谢谢。
推荐阅读
- python - 从嵌套列表中查找最接近给定值的值
- python - 如何创建一个列表,其中包含另一个列表中元素的所有频率?(在 Python 代码中)
- node.js - 在 MongoDB 内的 React 组件中存储选择选项输入值 - MERN 失败。将其存储为空字符串
- flutter - Firebase 实时数据库和 Flutter - 快照没有数据
- python - 为什么 time.time() 在异步循环中不是单调递增的?
- vue.js - 本地 Netlify 功能服务器给出奇怪的响应而不是 FaunaDB 数据
- html - 如何使数据表与我的主题兼容?
- javascript - 尝试连接到端口转发的数据库时套接字已关闭
- dpi - 无法使应用 DPI 感知 - 这不是重复的
- python - PyQt5 的口音