2013-02-24 27 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