2017-12-11 5 views
0

ここにありますが、私の単純なクラスです。後で私のコードで私はこのようなループに一般的な機能を使用します。Pythonのクラス()

for key, val in row.items() 

私はそれを変更したくない...ので、私の質問は、私はクラスでその項目()関数をシミュレートしないか、あります既存のforループでシームレスに動作するようにします。

+2

あなたが表示されている行の例えば前に 'items'でしたか? – schwobaseggl

+0

行= {"tan_id":tan_id、 "proc_name":proc_name} – gunslingor

+0

あなたは 'namedtuple'を使っていたはずのように@gunslingorは聞こえます。 –

答えて

3

あなたは、単に同じキーと値のペアを生成することによって、前dict.items()行動を模倣itemsメソッドを実装することができます

class row(object): 
    # ... 
    def items(self): 
     # this is the iterator behaviour of 'items' (Py3) or 'iteritems' (Py2) 
     yield 'tan_id', self.tan_id 
     yield 'proc_name', self.proc_name 
     # for the Py2 items behaviour, put these pairs into a list 
     # and return the list 

    # Or, more generally: 
    def items(self): 
     for slot in self.__slots__: 
      yield slot, getattr(self, slot) 
+0

2番目のオプションは、20個のクラスが同様の構造を持ちますが、ほとんどが20-50個の変数が定義されているため、動作すれば(テストする必要があります)理想的です。ありがとう。 – gunslingor