私は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
繰り返しごとに、構成ファイルの各セクションの構成設定を取得するために を呼び出します。誰かが別のアプローチを思い付くことができれば、それは大丈夫です! ありがとう!