2013-02-24 55 views
2

我的目标是设计一个Python API,允许客户端执行以下操作: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作为字段发生在 内__init__方法MentalDisorders
  5. 或许应该这样的DisorderCollection没有字段实例都存在,上述 被实现为一个简单的“转移呼叫”从__getattribute__到数据库中的一个关键 查找?在这种情况下,简单的md.disorders(没有指定键) 会返回什么?
+0

这似乎是做一个真正的Java方法。 – 2013-02-24 15:35:08

+0

因为我在Python中毫无用处,所以我来自Java,而且我很乐意学习如何不像Java那样可怜!请教我? – Robottinosino 2013-02-24 15:37:35

+0

什么是MentalDisorders,如果不是'DisorderCollection'。似乎你想要一个“是”的关系,而不是“拥有”。考虑:'m_disorders = MentalDisorders()','m_disorders.disorders ['...']'。我为什么重复自己? – Eric 2013-02-24 15:39:23

回答

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() 
+0

我明白了。 Upvoting .. – Robottinosino 2013-02-24 15:49:20

+1

甚至可能考虑让DisorderCollection成为collections.MutableSequence的子类。 http://docs.python.org/2/library/collections.html#collections.MutableSequence – JosefAssad 2013-02-24 15:53:54

+1

@JosefAssad:“collections.MappingView”看起来更合适 – Eric 2013-02-24 15:58:12