0

我有一个函数,它返回一个始终具有相同键的字典(通过网络发送并使用 json“字符串化”)。基本上我的功能是这样的:

def getTemps(self) -> dict:
    """
    get room and cpu temperature in °C as well as humidity in %
    """
    # send temperature request to server
    msg = {'type':'req', 'reqType':'temps'}
    self.send(msg)

    res = self.recieve()    # get response

    return res

你从这个函数得到的字典总是看起来像这样:

{'Room':float, 'CPU':float, 'hum':float}

所以我想知道是否有办法指定函数的返回类型,这样你就知道字典有哪些键:

def getTemps(self) -> Dict['Room':float, 'CPU':float, 'hum':float]

但这不起作用,因为它仅Dict[slice, slice, slice]在将鼠标悬停在函数上时才显示(我正在使用 vscode)。

我不认为这是非常有用的东西,但它可以让你的代码看起来更好,也更容易被别人使用。因此,如果有人知道这是否可能以及如何实现,我将非常感谢您的回复!

4

1 回答 1

0

考虑一下:

class Message:
    def __init__(self,room,cpu,hum):
        self.Room = room
        self.CPU = cpu
        self.hum = hum

return Message(room,cpu,hum)/或定义一个方法以dict在必要时在类中将其转换为。

这可能是唯一的方法。

更新:这既不是唯一也不是最好的方法,请参阅评论。

于 2021-08-18T10:18:45.587 回答