2

私の目的は、クライアントが次のことを実行できるようにするPythonAPIを設計することです。

md = MentalDisorders()
print(md.disorders['eating'])

食事関連の障害のリストを取得します。

これが私の刺し傷です。FAKE_DATABASEが実際のデータベースになると考えてください。この質問は、特に私がエイリアンであるPythonコンテキストで、インターフェイスの「感触」/「使いやすさ」に焦点を当てています。

#!/usr/bin/env python2.7

FAKE_DATABASE = {
  'anxiety': ['phobia', 'panic'],
  'personality': ['borderline', 'histrionic'],
  'eating': ['bulimia', 'anorexia'],
}

class MentalDisorders(object):
  # ... some methods and fields that make it worthwhile having a container class ...
  class DisorderCollection(object):
    def __getitem__(self, key):
      if key in FAKE_DATABASE:
        return FAKE_DATABASE[key]
      else:
        raise KeyError('Key not found: {}.'.format(key))
  def __init__(self):
    self.disorders = self.DisorderCollection()

def main():
  md = MentalDisorders()
  print(md.disorders['anxiety'])
  print(md.disorders['personality'])
  print(md.disorders['eating'])
  try:
    print(md.disorders['conduct'])
  except KeyError as exception:
    print(exception)

if __name__ == '__main__':
  main()
  1. 持っているDisorderCollectionことはまったくお勧めですか?
  2. その内部または外部でDisorderCollection定義する必要がありますか?MentalDisorders
  3. 正しいself.disorders方法でインスタンス化していますか?self.DisorderCollection
  4. DisorderCollectionフィールドとして使用されるaのインスタンス化は、 ?の__init__メソッド内から発生する必要がありMentalDisordersますか?
  5. おそらくフィールドインスタンスはまったく存在せず、上記はデータベース内のキールックアップへのDisorderCollection単純な「転送呼び出し」として実装する必要がありますか?__getattribute__その場合、単純なmd.disorders(キーが指定されていない)ものは何を返しますか?
4

1 に答える 1

3

これが私がそれを書くかもしれない方法です:

class DisorderCollection(object):
    def __getitem__(self, key):
        if key in FAKE_DATABASE:
            return FAKE_DATABASE[key]
        else:
            raise KeyError('Key not found: {}.'.format(key))

class MentalDisorders(DisorderCollection):
    # ... some methods and fields that make it worthwhile having a container class ...

class PhysicalDisorders(DisorderCollection):
    # Unless you plan to have multiple types of disorder collections with different methods, I struggle to see a point in the extra layer of classes.

def main():
    md = MentalDisorders()
    print(md['anxiety'])
    print(md['personality'])
    print(md['eating'])
    try:
        print(md['conduct'])
    except KeyError as exception:
        print(exception)

if __name__ == '__main__':
    main()
于 2013-02-24T15:48:06.057 に答える