如何使用关键字作为变量名? [英] How do I use a keyword as a variable name?
问题描述
我有带有变量from
,to
和rate
的以下类. from
是关键字.如果要在下面的init方法中使用它,编写它的正确方法是什么?
I have the following class with the variables from
, to
and rate
. from
is a keyword. If I want to use it in the init method below, what's the correct way to write it?
更多上下文:该类明确需要from
变量,因为它是另一位开发人员用另一种语言编写的POST端点所需的json的一部分.因此,更改变量名称是不可能的.
More context: The class needs the from
variable explicitly as it's part of a json required by a POST endpoint written up by another developer in a different language. So changing the variable name is out of the question.
class ExchangeRates(JsonAware):
def __init__(self, from, to, rate):
self.from = from
self.to = to
self.rate = rate
JsonAware代码:
JsonAware code:
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)
GenericEncoder代码:
GenericEncoder code:
class GenericEncoder(json.JSONEncoder):
def default(self, obj):
return obj.__dict__
推荐答案
如注释中所述,from
是Python关键字,因此不能将其用作变量名或属性名.因此,您需要使用备用名称,并在读取或写入JSON数据时进行转换.
As mentioned in the comments, from
is a Python keyword so you can't use it as a variable name, or an attribute name. So you need to use an alternative name, and do a conversion when reading or writing the JSON data.
要进行输出转换,可以为json.dumps
提供一个新的编码器.您可以通过覆盖ExchangeRates.json
方法来实现.要进行输入转换,请覆盖ExchangeRates.from_json
.
To do the output conversion you can supply a new encoder for json.dumps
; you can do that by overriding the ExchangeRates.json
method. To do the input conversion, override ExchangeRates.from_json
.
两种情况下的策略相似:我们创建字典的副本(因此我们不会对原始字典进行变异),然后创建具有所需名称和值的新键,然后删除旧键.
The strategy is similar in both cases: we create a copy of the dictionary (so we don't mutate the original), then we create a new key with the desired name and value, then delete the old key.
这是一个快速的演示,已在Python 2.6和3.6上进行了测试:
Here's a quick demo, tested on Python 2.6 and 3.6:
import json
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 ExchangeRatesEncoder(json.JSONEncoder):
def default(self, obj):
d = obj.__dict__.copy()
d['from'] = d['frm']
del d['frm']
return d
class ExchangeRates(JsonAware):
def __init__(self, frm, to, rate):
self.frm = frm
self.to = to
self.rate = rate
def json(self):
return json.dumps(self, cls=ExchangeRatesEncoder)
@classmethod
def from_json(cls, json):
d = json.copy()
d['frm'] = d['from']
del d['from']
return cls(**d)
# Test
a = ExchangeRates('a', 'b', 1.23)
print(a.json())
jdict = {"from": "z", "to": "y", "rate": 4.56, }
b = ExchangeRates.from_json(jdict)
print(b.json())
典型输出
{"from": "a", "to": "b", "rate": 1.23}
{"from": "z", "to": "y", "rate": 4.56}
这篇关于如何使用关键字作为变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!