我是相當新的Python和有關於以下類問題:最佳實踐定義實例變量時
class Configuration:
def __init__(self):
parser = SafeConfigParser()
try:
if parser.read(CONFIG_FILE) is None:
raise IOError('Cannot open configuration file')
except IOError, error:
sys.exit(error)
else:
self.__parser = parser
self.fileName = CONFIG_FILE
def get_section(self):
p = self.__parser
result = []
for s in p.sections():
result.append('{0}'.format(s))
return result
def get_info(self, config_section):
p = self.__parser
self.section = config_section
self.url = p.get(config_section, 'url')
self.imgexpr = p.get(config_section, 'imgexpr')
self.imgattr1 = p.get(config_section, 'imgattr1')
self.imgattr2 = p.get(config_section, 'imgattr2')
self.destination = p.get(config_section, 'destination')
self.createzip = p.get(config_section, 'createzip')
self.pagesnumber = p.get(config_section, 'pagesnumber')
是否確定到另一個函數在這個例子中添加更多的實例變量,get_info
,或在構造函數中定義所有實例變量是否是最佳實踐?如果我在整個地方定義新的實例變量,它不會導致意大利麪條代碼嗎?
編輯:我用這個代碼與一個簡單的圖像刮刀。通過get_section
我返回配置文件中的所有部分,然後遍歷它們以訪問我從中刮取圖像的每個站點。對於每次迭代,我撥打get_section
以獲取配置文件中每個部分的配置設置。 如果任何人都可以想出另一種方法,它會沒事的!謝謝!
http://stackoverflow.com/questions/2964230/python-how-should-i-make-instance-variables-available –
'自我。應該在__init __()'的開頭設置__parser = None。原因是'__init __()'被稱爲*已經存在的*對象的第一個代碼。如果解析器無法讀取配置文件並引發異常,則該異常可能會被catched elswhere(程序可能不會終止)。然後,Configuration類的對象仍然存在,後面的get_info()會導致* AttributeError:Configuration實例沒有屬性'__parser'。 – pepr
@pepr我應該讀你回答我應該在'__init __。py'的開頭添加'self .__ parser = None'的方式還是建議將解析器初始化從'__init __。py'移動到另一個函數? – happygoat