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?
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 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 code:
class GenericEncoder(json.JSONEncoder):
def default(self, obj):
return obj.__dict__
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…