如何使用关键字作为变量名?

2024-05-21 05:04:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个变量为fromtorate的类。from是一个关键字。如果我想在下面的in it方法中使用它,正确的方法是什么?

更多上下文:类显式地需要from变量,因为它是另一个开发人员用不同语言编写的POST端点所需的json的一部分。所以改变变量名是不可能的。

class ExchangeRates(JsonAware):
    def __init__(self, from, to, rate):
        self.from = from
        self.to = to
        self.rate = rate

JsonAware代码:

class PropertyEquality(object):
    def __eq__(self, other):
        return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__)

    def __ne__(self, other):
        return not self.__eq__(other)

    def __repr__(self):
        return '%s(%s)' % (self.__class__.__name__, ', '.join(['%s=%s' % (k, v) for (k, v) in self.__dict__.items()]))

class JsonAware(PropertyEquality):
    def json(self):
        return json.dumps(self, cls=GenericEncoder)

    @classmethod
    def from_json(cls, json):
        return cls(**json)

通用代码:

class GenericEncoder(json.JSONEncoder):
    def default(self, obj):
        return obj.__dict__

Tags: to方法代码infromselfjsonreturn