私は、変数from
,to
およびrate
を持つ以下のクラスを持っています。 from
はキーワードです。下のinitメソッドでそれを使いたいのであれば、それを書く正しい方法は何ですか?キーワードを変数名として使用するにはどうすればよいですか?
その他のコンテキスト:別の開発者が別の言語で書いたPOSTエンドポイントに必要なjsonの一部であるため、クラスにはfrom
変数が明示的に必要です。したがって、変数名の変更は問題外です。
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)
GenericEncoderコード:
class GenericEncoder(json.JSONEncoder):
def default(self, obj):
return obj.__dict__
キーワードであるため、識別子として使用することはできません。それがキーワードの意味です!例えば代わりに 'from_'を使います。 – jonrsharpe
'from'は3回使用され、3回赤く表示されますが、** kwargsを使用してキーワードや何かをエスケープする必要はありませんか? – user4659009
'setattr(self、 'from'、kwargs.get( 'from'))'のようにすることもできますが、辞書を使って渡す必要があります。 ..、** {'from':whatever}) 'にアクセスし、' getattr(rates、from ') 'を介してのみアクセスできます。名前を変更するのはあまり煩雑ではありません**。例えば、 http://stackoverflow.com/q/9746838/3001761 – jonrsharpe