为什么陈述会影响私有属性的存在?

时间:2019-02-06 10:19:38

标签: python python-3.x

我正在练习python OOP并被卡住。 _filename__init__方法中明确定义,但会引发错误。我不知道为什么。

import os
import pickle
import sys

config_directory = 'configs/'   # added:  see below

class ConfigKeyError(Exception):
    def __init__(self, this, key):
        self.key = key
        self.keys = this.keys()
    def __str__(self):
        return ('key "{0}" not found.  Available keys:' '({1})'.format(self.key, ', '.join(self.keys)))

class ConfigDict(dict):
    config_directory = 'configs/'
    def __init__(self, picklename):
        self._filename = config_directory + picklename + '.pickle'
        if not os.path.isfile(self._filename):
            with open(self._filename, 'wb') as fh:
                pickle.dump({}, fh)
        with open(self._filename, 'rb') as fh:
            config_content = pickle.load(fh)
            self.update(config_content)
            print(self._filename)

    def __getitem__(self, key):
        if not key in self:
            raise ConfigKeyError(self, key)
        return dict.__getitem__(self, key)

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)
        with open(self._filename, 'wb') as fh:
            pickle.dump(self, fh)


cd = ConfigDict('config_file')
print(cd._filename)

运行此命令时,会出现以下错误。

Traceback (most recent call last):
  File "assignment5.py", line 38, in <module>
    cd = ConfigDict('config_file')
  File "assignment5.py", line 23, in __init__
    config_content = pickle.load(fh)
  File "assignment5.py", line 34, in __setitem__
    with open(self._filename, 'wb') as fh:
AttributeError: 'ConfigDict' object has no attribute '_filename'

但是,如果我在原始代码中添加以下if语句。

def __setitem__(self, key, value):
    dict.__setitem__(self, key, value)
    if '_filename' in dir(self):
        with open(self._filename, 'wb') as fh:
            pickle.dump(self, fh)

错误消失了,一切正常。

摘要:
没有if语句->找不到属性'_filename'
使用if语句->找到属性'_filename'

为什么会这样?

1 个答案:

答案 0 :(得分:1)

我在系统中运行了您的代码,并且无需任何修改即可完美运行。

enter image description here

能否请您检查是否有其他具有相同类ConfigDict的模块?也许那个模块/类没有给定的属性,而Python正在选择该类而不是这个类。