2016-11-19 28 views
2

我想使用括號表達式來訪問dict中的值,但沒有任何其他dict功能。重複使用字典的功能是pythonic,但不適用於類似字典的功能?

在下面的示例中,我使用表達式variable[something]以與dict相同的方式查詢variabledict後面沒有其他功能,計算返回的是什麼(something'color'"hello")。

import random 

class ColDict(dict): 
    def __init__(self, *args): 
     dict.__init__(self, args) 
     self.colors = ['blue', 'white', 'red'] 
    def __getitem__(self, item): 
     if item == 'color': 
      random.shuffle(self.colors) 
      return(self.colors[0]) 
     else: 
      return("hello") 

if __name__ == "__main__": 
    col = ColDict() 
    print(col['color'], col['color'], col['something']) # red white hello (changes on each call) 

此代碼按預期工作。

我想了解的是dict功能(支架調用)的重用是py pyonic,還是最後可以接受。

注意:我明白,這可以通過其他方式來實現(liek一個函數),但我特別重複使用方括號調用。 重複使用,不濫用(這是我的問題的核心)

+2

我看不出你爲什麼要讓這個類從'dict'派生出來。那是什麼給你買的? –

+0

@JohnZwinck:使用括號呼叫的能力。 – WoJ

+1

這個問題很基於觀點。 ***在我看來*** –

回答

5

如果你不需要從字典的任何功能,只是提供__getitem__()

import random 

class ColDict: 
    def __init__(self, *args): 
     self.colors = ['blue', 'white', 'red'] 
    def __getitem__(self, item): 
     if item == 'color': 
      return random.choice(self.colors) 
     else: 
      return("hello") 

if __name__ == "__main__": 
    col = ColDict() 
    print(col['color'], col['color'], col['something']) # red white hello (changes on each call) 

read more about it

+0

而且由於OP使用Python 3,因此從'object'繼承也不是必需的。 –

+0

thx,你是對的 – dahrens

3

是的,它是unpythonic 。沒有必要繼承字典,因爲您獲得的只是稍長的方法名稱和屬性訪問語法。製作一個沒有顯式繼承的普通類來返回隨機顏色。因爲你的班級的__getitem__對每一個其他值都返回一個常量,所以用一個可以用特定名稱檢索的常量來創建一個類或實例變量,而不是「不是color」的任何東西。如果您擔心用戶無法輸入隨機屬性名稱來訪問該常量,請記住「應該有一個 - 最好只有一個 - 顯而易見的方法」(來自PEP-20, The Zen of Python)。

import random 

class ColObj: 
    other = 'hello' 
    def __init__(self, *args): 
     self.colors = ['blue', 'white', 'red'] 
    def color(self): 
      return random.choice(self.colors) 

if __name__ == "__main__": 
    col = ColObj() 
    print(col.color, col.color, col.other) 

如果這是所有的類呢,我看不出太大的必要一類的話 - 你可以簡單地定義一個函數color和一個字符串(或其他常數)other

import random 

other = 'hello' 
def color(colors=('blue', 'white', 'red')): 
     return random.choice(colors) 

if __name__ == "__main__": 
    print(color(), color(), other) 
+0

謝謝你的擴展解釋 - 實際用例更復雜,我只是寫了一個工作示例來解決問題。 – WoJ

+1

@WoJ - 我的期望是一樣的。我只是想強調只有在增加價值時才應使用OOP。 – TigerhawkT3

+0

@WoJ:由於TigerhawkT3提到,你不需要在這裏上課 –