2016-10-02 72 views
0

用戶數據,如下所示:當使用一個類而不是一個字典的

user = {"id": 1, "firstName": "Bar", "surname": "Foosson", "age": 20} 

被髮送到經由JSON的應用程序。

在代碼中的許多地方,下面就做:

user["firstName"] + " " + user["surname"] 

這使我相信,一個功能可用於:

def name(user): 
    return user["firstName"] + " " + user["surname"] 

這反過來又導致我相信,代碼應該使用User類改爲使用name方法重構。你是否同意並且有沒有重構代碼來使用類的爭論?

+3

除此之外,使用'「{的firstName} {姓}」。格式(**用戶)'。 ;) –

+0

另一方面:在Python中,這些東西被稱爲「字典」(它們的類型是「字典」)。稱他們爲「地圖」可能會引起混淆(因爲「地圖」)。 – 2016-10-02 18:28:15

+2

即使不需要'def name(user)',我也會使用一個類。作爲一般規則,如果'dict'的鍵是固定的(你總是希望有firstName,姓氏),這表明你不應該使用'dict'。 – zvone

回答

1

我敢肯定,由於需要編寫樣板代碼,您對使用類猶豫不決。

但有一個很好的圖書館,可以讓你的生活更輕鬆:attrs

雕文有一個自稱題目的帖子:The One Python Library Everyone Needs。當然,這是一個自以爲是的一塊,但這裏是從它的Examples page報價:

>>> @attr.s 
... class Coordinates(object): 
...  x = attr.ib() 
...  y = attr.ib() 

默認情況下,所有的功能被添加,讓你立刻擁有一個功能齊全的數據類用一個漂亮的repr字符串和比較方法。

>>> c1 = Coordinates(1, 2) 
>>> c1 
Coordinates(x=1, y=2) 
>>> c2 = Coordinates(x=2, y=1) 
>>> c2 
Coordinates(x=2, y=1) 
>>> c1 == c2 
False 

這是一個非常方便的庫,所以檢查出來。

這是你的User類的例子:

import attr 

@attr.s 
class User(object): 

    id = attr.ib() 
    firstName = attr.ib() 
    surname = attr.ib() 
    age = attr.ib() 

    @property 
    def name(self): 
     return '{0.firstName} {0.surname}'.format(self) 

user_dict = {'id': 1, 'firstName': 'Bar', 'surname': 'Foosson', 'age': 20} 
user = User(**user_dict) 
assert user.name == 'Bar Foosson' 
1

字典是偉大的存儲和檢索,但如果你需要最重要的是更多的功能,一類通常要走的路。這樣你也可以保證設置某些屬性等。

對於你的情況,如果用戶的屬性是隻讀的,我的方法實際上是使用namedtuple。你得到的屬性,記憶效率的不變性,你仍然可以設置name到一個預先定義的方法中使用,就像你在一個類中使用property

from collections import namedtuple 

@property 
def name(self): 
    return '{} {}'.format(self.firstName, self.surname) 

User = namedtuple('User', 'id firstName surname age') 
User.name = name 

user = User(1, 'Bar', 'Foosson', 20) 
print(user.name) # Bar Foosson 

user = User(2, 'Another', 'Name', 1) 
print(user.name) # Another Name 
相關問題