我的目標是設計一個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()
- 是具有
DisorderCollection
建議呢? DisorderCollection
應該在MentalDisorders
之內還是在其外面定義?- 正在實例化
self.disorders
通過self.DisorderCollection
正確嗎? - 實例化
DisorderCollection
作爲字段發生在 內__init__
方法MentalDisorders
? - 或許應該這樣的
DisorderCollection
沒有字段實例都存在,上述 被實現爲一個簡單的「轉移呼叫」從__getattribute__
到數據庫中的一個關鍵 查找?在這種情況下,簡單的md.disorders
(沒有指定鍵) 會返回什麼?
這似乎是做一個真正的Java方法。 – 2013-02-24 15:35:08
因爲我在Python中毫無用處,所以我來自Java,而且我很樂意學習如何不像Java那樣可憐!請教我? – Robottinosino 2013-02-24 15:37:35
什麼是MentalDisorders,如果不是'DisorderCollection'。似乎你想要一個「是」的關係,而不是「擁有」。考慮:'m_disorders = MentalDisorders()','m_disorders.disorders ['...']'。我爲什麼重複自己? – Eric 2013-02-24 15:39:23