2011-12-30 1 views
0

私は週についての情報を格納するクラスを持っている:のPython(ジャンゴ)クラスその属性へのエイリアス/過負荷リストインデックスの挙動

from django.db import models 

#A django model, so can't subclass list (at least not easily) 
class MyWeek(models.Model): 
    sunday = "foo" 
    monday = "foo" 
    tuesday = "foo" 
    wednesday = "foo" 
    thursday = "foo" 
    friday = "foo" 
    saturday = "foo" 

私はクラスの場合と同様に、これらの属性にアクセスできるようにしたいのですが

Pythonについては、すべてが過負荷になるようなものがわかっていれば、これが可能で簡単だと思います。

私は@property考えてきましたが、私はそれにアクセスするために変数を使用できるようにしたいので、それはあまり役に立ちません。

#I want to be able to do this 
aweek[somevar] = "bar" 

#and via property, i'd have to use exec 
#and this is just ugly and scary from an "oh god, what could somevar be" perspective 
exec("aweek.%s = 'bar'" % somevar) 

#Or, as kojiro pointed out below, it could be done like this: 
setattr(aweek, "somevar", "bar") 

感謝。

編集:作業するコードは、オーバーロードする右の方法で助けるため小次郎するhattip:

# overload [] 
def __getitem__(self, index):  
    index = int(index) #will raise value error if uncoercable, this is desired behavior 
    if index < 0 or index > 6: 
     raise ValueError("Requires an integer index between 0 and 6, monday is 0 sunday is 6") 
    if index == 0: 
     return self.monday 
    elif index == 1: 
     return self.tuesday 
    elif index == 2: 
     return self.wednesday 
    elif index == 3: 
     return self.thursday 
    elif index == 4: 
     return self.friday 
    elif index == 5: 
     return self.saturday 
    elif index == 6: 
     return self.sunday 

# overload set [] 
def __setitem__(self, index, item): 
    index = int(index) #will raise value error if uncoercable, this is desired behavior 
    if index < 0 or index > 6: 
     raise ValueError("Requires an integer index between 0 and 6, monday is 0 sunday is 6") 
    if index == 0: 
     self.monday = item 
     return 
    elif index == 1: 
     self.tuesday = item 
     return 
    elif index == 2: 
     self.wednesday = item 
     return 
    elif index == 3: 
     self.thursday = item 
     return 
    elif index == 4: 
     self.friday = item 
     return 
    elif index == 5: 
     self.saturday = item 
     return 
    elif index == 6: 
     self.sunday = item 
     return 
+3

ところで、あなたは上記のために 'exec()'を使う必要はありません。 'setattr(aweek、" somevar "、" bar ")'はうまく動作し、間違いなく好ましいでしょう。 [続きを読む](http://docs.python.org/library/functions.html#setattr) – kojiro

+0

ああ、いいね。私は以前setattrを使っていませんでしたが、これははるかに良い方法です、私は将来それを使うつもりです。 – Ted

答えて

4

はPythonでリストのようなオブジェクトを作成するには、次のメソッドを作成する必要があります。

__len__を、__getitem____setitem____delitem____iter__、および__contains__

Link to explanatory example.

+0

すごく、ありがとう、私はそれが簡単だと思った。 – Ted

+1

あるいは '' 'list'''からクラスを継承し、上のいくつかのフィールドをオーバーライドできます。 –

+0

@PavelShvedov良い点、私は "あなたが必要な...次の"と言っていたはずです。すでに作成している場合は作成する必要はありません。 :) – kojiro

関連する問題