2

我的目标是设计一个允许客户端执行以下操作的 Python API:

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 回答