2016-06-22 12 views
1

私は、変数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__ 
+14

キーワードであるため、識別子として使用することはできません。それがキーワードの意味です!例えば代わりに 'from_'を使います。 – jonrsharpe

+0

'from'は3回使用され、3回赤く表示されますが、** kwargsを使用してキーワードや何かをエスケープする必要はありませんか? – user4659009

+5

'setattr(self、 'from'、kwargs.get( 'from'))'のようにすることもできますが、辞書を使って渡す必要があります。 ..、** {'from':whatever}) 'にアクセスし、' getattr(rates、from ') 'を介してのみアクセスできます。名前を変更するのはあまり煩雑ではありません**。例えば、 http://stackoverflow.com/q/9746838/3001761 – jonrsharpe

答えて

2

コメントに記載されているように、fromはPythonキーワードなので、変数名または属性名として使用することはできません。だからあなたは別の名前を使用し、JSONデータを読み書きするときに変換を行う必要があります。

出力変換を行うには、json.dumpsの新しいエンコーダを使用できます。 ExchangeRates.jsonメソッドをオーバーライドすることでこれを行うことができます。入力変換を行うには、ExchangeRates.from_jsonを上書きします。

戦略はどちらの場合も同様です。辞書のコピーを作成して(元のものに変更しないように)、目的の名前と値で新しいキーを作成し、古いキーを削除します。

ここではPython 2.6と3.6でテストされ、迅速デモ、だ:のFrom_と

TO_:

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} 
1

同義語を使用してください。代わりに "origin"または "source"を試してください。

0

は、お好みの名前にアンダースコアを追加します。 (PEP 8参照)

class ExchangeRates(JsonAware): 
    def __init__(self, from_, to_, rate): 
     self.from = from_ 
     self.to = to_ 
     self.rate = rate 
関連する問題