Python嵌套类(ParentChild[类的新成员])

2024-09-30 05:18:55 发布

您现在位置: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中的类比较陌生,我不太清楚如何构建类,以便调用日期,然后调用获取相应数据的时间。我假设一个嵌套类需要在代码中有一个类似“父-子”的关系,但是我不知道如何做到这一点。你知道吗


Tags: 数据代码selftype时间tempclass例子
1条回答
网友
1楼 · 发布于 2024-09-30 05:18:55

虽然在Python中数字不被认为是有效的标识符(但这对于trolling来说可能很有趣: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现在会给你新的值。但是,如果您关心性能,并且只使用其中的一半,那么这一个可能比存储结果快,但是如果您多次访问它们,这将慢得多。你知道吗

如何使用:

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

相关问题 更多 >

    热门问题