python - 用 Super 构建合适的 Python Facade 类?

标签 python inheritance super facade method-resolution-order

我以为我已经掌握了 Super() 的多重继承,并试图在 Facade 类中使用它,但我遇到了一个奇怪的错误。我正在使用名为 Fireworks 的制作精良的 Python Workflow 软件,但类和工作流任务的结构非常严格,因此我创建了一个 Facade 类以便于使用。

下面是工作流任务的基本结构:

class BgwInputTask(FireTaskBase):

    required_params = ['structure', 'pseudo_dir', 'input_set_params', 'out_file']
    optional_params = ['kpoints', 'qshift', 'mat_type']

    def __init__(self, params): 
        self.structure = Structure.from_dict(params.get('structure').as_dict())
        self.pseudo_dir = params.get('pseudo_dir')
        self.kpoints = params.get('kpoints', None)
        self.qshift = params.get('qshift', None)
        self.isp = params.get('input_set_params')
        self.run_type = params.get('run_type', None)
        self.mat_type = params.get('mat_type', 'metal')
        self.filename = params.get('out_file')

        '''
        misc code for storing pseudo_potentials in:
        self.pseudo_files
        self.occupied_bands
        etc...
        '''

        params = {'structure': self.structure, 'pseudo_dir': self.pseudo_dir,
            'kpoints': self.kpoints, 'qshift': self.qshift,
            'input_set_params': self.isp, 'run_type': self.run_type,
            'mat_type':self.mat_type, 'out_file': self.filename}
        self.update(params)

    def write_input_file(self, filename):
        <code for setting up input file format and writing to filename>

我用下面的 super 构造了我的 Facade 类:

class BgwInput(BgwInputTask):

    def __init__(self, structure, pseudo_dir, isp={},
                kpoints=None, qshift=None, mat_type='semiconductor',
                out_file=None):

        self.__dict__['isp'] = isp
        self.__dict__['run_type'] = out_file.split('.')[0]
        self.__dict__['params'] = {'structure': structure, 'pseudo_dir': pseudo_dir,
            'kpoints': kpoints, 'qshift': qshift,
            'input_set_params': self.isp, 'mat_type': mat_type,
            'out_file': out_file, 'run_type': self.run_type}
        print("__init__: isp: {}".format(self.isp))
        print("__init__: runtype: {}".format(self.run_type))

        super(BgwInput, self).__init__(self.params)

    def __setattr__(self, key, val):
        self.proc_key_val(key.strip(), val.strip()) if isinstance(
            val, six.string_types) else self.proc_key_val(key.strip(), val)

    def proc_key_val(self, key, val):
        <misc code for error checking of parameters being set>
        super(BgwInput, self).__dict__['params']['input_set_params'].update({key:val})

除了一个让我感到困惑的小警告外,这很好用。创建 BgwInput 的新实例时,它不会创建一个空实例。在先前实例中设置的输入集参数以某种方式被转移到新实例中,但不是 kpointsqshift。例如:

>>> epsilon_task = BgwInput(structure, pseudo_dir='/path/to/pseudos', kpoints=[5,5,5], qshift=[0, 0, 0.001], out_file='epsilon.inp')
__init__: isp: {}
__init__: runtype: epsilon

>>> epsilon_task.epsilon_cutoff = 11.0
>>> epsilon_task.number_bands = 29


>>> sigma_task = BgwInput(structure, pseudo_dir='/path/to/pseudos', kpoints=[5,5,5], out_file='sigma.inp')
__init__: isp: {'epsilon_cutoff': 11.0, 'number_bands': 29}
__init__: runtype: sigma

但是,如果我将 Facade 类中的 self.__dict__['isp'] = isp 更改为 self.__dict__['isp'] = isp if isp else {} 一切似乎都按预期工作。在先前实例中设置的参数不会转移到新实例中。那么,为什么 Facade 类不默认为 isp={}(假设这是 __ init __ 中的默认值),如果在创建时没有给定输入集参数,它应该如此?它从哪里提取先前的参数,因为默认值应该是一个空白字典?

需要说明的是,我有一个解决方案可以使 Facade 类按预期运行(通过将 Facade 中的 isp 更改为 self.__dict__['isp' ] = isp if isp else {}),但我想弄清楚为什么需要这样做。我相信我遗漏了 super 或 Python 中的方法解析顺序的一些基本内容。我很好奇为什么会发生这种情况并试图扩展我的知识库。

下面是 Facade 类的方法解析顺序。

>>> BgwInput.__mro__

(pymatgen.io.bgw.inputs.BgwInput,
pymatgen.io.bgw.inputs.BgwInputTask,
fireworks.core.firework.FireTaskBase,
collections.defaultdict,
dict,
fireworks.utilities.fw_serializers.FWSerializable, 
object)

最佳答案

python 中的可变默认参数并不像您期望的那样工作;您的函数定义(省略不相关的参数):

def __init__(self, ..., isp={}, ...):
   <CODE>

等同于:

DEFAULT_ISP = {}
def __init__(self, ..., isp=DEFAULT_ISP, ...):
   <CODE>

(除了 DEFAULT_ISP 变量不可用。)

上面的代码清楚地表明你的两个任务正在使用相同的 isp 字典,这显然是由属性 setter 修改的。

关于python - 用 Super 构建合适的 Python Facade 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37554187/

相关文章:

Python - 完全相同的循环工作不一致 'int'对象不可迭代 - 不迭代 int

c# - 存储派生对象的泛型类列表

python - 在 Python 3 中调用 super() 的 4 种方法中的哪一种?

python - 从包中安装 Python,终端没有更新?

python - 使用 Pandas 数据框创建一个类(更新)

java - 将父类(super class)实例传递给其构造函数是否是更好的做法?

python - 如何从孙子类调用 super 方法?

java - 访问列表中的父类

python - 如何在 Pandas 中连接 MultiIndex

java - java中如何判断一个对象外部扩展了什么