2016-07-06 66 views
1

我有這個數據Python的 - 嵌套類(親子[新的類])

{Wednesday : {22 : {Type = x, 
        Temp = x, 
        Speed = x, 
        Direction = x} 
      {23 : {Type = x, 
        Temp = x, 
        Speed = x, 
        Direction = x} 

我試圖寫一個類,這樣我就可以通過調用作爲一個例子來訪問它,這將使我X.

到目前爲止我的代碼是這樣的:

class Weather(object): 
     def __init__(self, wtype, wtemp, wspeed, wdirection): 
      self.type = wtype 
      self.temp = wtemp 
      self.speed = wspeed 
      self.direction = wdirection 

這使我獲得的數據時的日期時調用:

Wednesday.Temp 
>>> 22 

但是我也需要按時間和日期分配數據,所以在撥打"Wednesday.22.Type"時我會得到我們的具體日期。

我是Python新興的類,我不太確定如何構建該類,以便我可以調用日期,然後獲取相應數據。我假設一個嵌套類需要在代碼中有一個「父子」像關係,但我不知道如何做到這一點。

+0

'22'是不是一個有效的標識符。 – CodenameLambda

+0

@CodingLambdas堅持嵌套字典會更好嗎? –

+0

我正在寫一個答案。 – CodenameLambda

回答

1

雖然數字不被認爲是有效的標識符在Python(但可能對曳很有趣:0 = 1 = 2 = 3 = 42),像_3的,但一般認爲是「私人」屬性由Python社區(我自己包括),所以我使用at後跟數字。我認爲像訪問字典那樣訪問它會更好。

這是我的承擔。如果您不需要關聯的功能,請刪除這些方法。

class SpecificWeather(object): 
    def __init__(self, data): 
     self.data = data 

    @property 
    def type(self): 
     return self.data["Type"] 

    @property 
    def temperature(self): 
     return self.data["Temp"] 

    @property 
    def speed(self): 
     return self.data["Speed"] 

    @property 
    def direction(self): 
     return self.data["Direction"] 


class Weather(object): 
    def __init__(self, data): # data is the dictionary 
     self.data = data 

    def __getitem___(self, item): # for wednesday[22].type 
     return SpecificWeather(self.data[item]) 

    def __getattr__(self, name): # for wednesday.at22.type 
     if name.startswith("at"): 
      return SpecificWeather(self.data[int(name[2:])]) 
     raise AttributeError() 

    @property 
    def type(self): 
     # TODO: Return the average type or something like that 

    @property 
    def temperature(self): 
     # TODO: Return the average temperature or something like that 

    @property 
    def speed(self): 
     # TODO: Return the average speed or something like that 

    @property 
    def direction(self): 
     # TODO: Return the average direction or something like that 

該解決方案使用property了很多,這有很大的優勢:如果你改變了溫帶22,wednesday[22].temperature現在會給你新的價值。但是,如果你關心性能,並且只使用其中的一半,那麼這個比存儲結果更快,如果你甚至多次訪問它們,這將會慢很多。

如何使用它:

wednesday = Weather({ 
    22: { 
     'Type': ..., 
     'Temp': 30, 
     'Speed': ..., 
     'Direction': ... 
    }, 
    23: { 
     'Type': ..., 
     'Temp': 28, 
     'Speed': ..., 
     'Direction': ... 
    } 
}) 

print(wednesday.at22.temperature) # gives 30 
print(wednesday[23].temperature) # gives 28 
+0

不好意思問,但是你能否加入一個例子來演示,我不完全理解如何使用它。 –

+0

@SylentNyte好的。 – CodenameLambda

+0

謝謝,這正是我所需要的,但是當我嘗試使用這個代碼時print'(wednesday [23] .temperature)''TypeError:'Weather'object does not support indexing' –