gpt4 book ai didi

Python - 嵌套类(父子类[类新手])

转载 作者:太空宇宙 更新时间:2023-11-03 16:22:57 25 4
gpt4 key购买 nike

我有这个数据

{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 中的类很陌生,我不太确定如何构建该类,以便我可以调用日期,然后调用获取相应数据的时间。我假设嵌套类需要在代码中具有类似“父子”的关系,但是我不确定如何做到这一点。

最佳答案

尽管数字在 Python 中不被视为有效标识符(但这对于恶搞来说可能很有趣:0 = 1 = 2 = 3 = 42),但诸如 _3 是,但通常被 python 社区(包括我自己)认为是“私有(private)”属性,所以我使用 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 现在将为您提供新的温度值(value)。然而,如果您关心性能,并且只使用其中的一半,那么这可能比存储结果更快,但如果您多次访问它们,这会慢很多。

如何使用:

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

关于Python - 嵌套类(父子类[类新手]),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38235151/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com