在python中,对类变量的赋值不存在

2024-05-29 09:37:04 发布

您现在位置: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解释器执行,因此我需要对系统路径进行一些巫毒操作。你知道吗

我有一个代码,实际上看起来像:


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/生成管理器.py地址:

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

在工厂/植物.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

Tags: pathpyselfinitsysminnumclass
1条回答
网友
1楼 · 发布于 2024-05-29 09:37:04

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

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

stem = stems.Stem()

也许有人能给我解释一下背后的逻辑?谢谢。你知道吗

相关问题 更多 >

    热门问题