我有以下带有变量 from
、to
和 rate
的类。 来自
是 keyword .如果我想在下面的init方法中使用它,正确的写法是什么?
更多上下文:该类显式需要 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__
最佳答案
在您的首选名称中添加一个下划线:来自 _ 和 _
(参见 PEP 8)
class ExchangeRates(JsonAware):
def __init__(self, from_, to_, rate):
self.from = from_
self.to = to_
self.rate = rate
关于python - 如何使用关键字作为变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37968516/