如何使用关键字作为变量名?
How do I use a keyword as a variable name?
我有以下 class 和变量 from
、to
和 rate
。 from
是关键字。如果我想在下面的init方法中使用它,正确的写法是什么?
更多上下文:class 明确需要 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__
使用同义词。请尝试 "origin" 或 "source"。
如评论中所述,from
是一个 Python 关键字,因此您不能将其用作变量名或属性名。所以你需要使用替代名称,并在读取或写入 JSON 数据时进行转换。
要进行输出转换,您可以为 json.dumps
提供一个新的编码器;您可以通过覆盖 ExchangeRates.json
方法来做到这一点。要进行输入转换,请覆盖 ExchangeRates.from_json
.
两种情况下的策略相似:我们创建字典的副本(因此我们不会改变原始字典),然后我们创建一个具有所需名称和值的新键,然后删除旧键。
这是一个快速演示,在 Python 2.6 和 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}
在您的首选名称中添加一个下划线:from_ 和 to_
(见PEP 8)
class ExchangeRates(JsonAware):
def __init__(self, from_, to_, rate):
self.from = from_
self.to = to_
self.rate = rate
我有以下 class 和变量 from
、to
和 rate
。 from
是关键字。如果我想在下面的init方法中使用它,正确的写法是什么?
更多上下文:class 明确需要 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__
使用同义词。请尝试 "origin" 或 "source"。
如评论中所述,from
是一个 Python 关键字,因此您不能将其用作变量名或属性名。所以你需要使用替代名称,并在读取或写入 JSON 数据时进行转换。
要进行输出转换,您可以为 json.dumps
提供一个新的编码器;您可以通过覆盖 ExchangeRates.json
方法来做到这一点。要进行输入转换,请覆盖 ExchangeRates.from_json
.
两种情况下的策略相似:我们创建字典的副本(因此我们不会改变原始字典),然后我们创建一个具有所需名称和值的新键,然后删除旧键。
这是一个快速演示,在 Python 2.6 和 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}
在您的首选名称中添加一个下划线:from_ 和 to_
(见PEP 8)
class ExchangeRates(JsonAware):
def __init__(self, from_, to_, rate):
self.from = from_
self.to = to_
self.rate = rate