我有一个课程,存储一周的信息:
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"
我希望能够像访问列表一样访问这些属性:
aweek = Myweek()
#I want this
aweek[0] = "bar"
myvar = aweek[1]
#To be shorthand for this
aweek.monday = "bar"
myvar = aweek.tuesday
#and of course
aweek[7]
ValueError/IndexError: Week indexes monday to 0 and sunday to 6, there is no 7
关于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 to kojiro for help with the right methods to overload:
# 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
要在python中创建类似列表的对象,需要创建以下方法:
__len__
、__getitem__
、__setitem__
、__delitem__
、__iter__
和__contains__
Link to explanatory example.
相关问题 更多 >
编程相关推荐