我正在练习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'
为什么会这样?