【发布时间】:2012-04-30 08:09:59
【问题描述】:
class Screening(models.Model):
def get_omitted_1(self):
return OmittedInformationReason.objects.get(pk=self.omitted_1).name
get_omitted_1 = property(get_omitted_1)
我想访问screening_instance.get_omitted_1、screening_instance.get_omitted_2 到screening_instance.get_omitted_10。有没有更好的方法来做到这一点,而无需为每个案例创建 get_omitted_1、get_omitted_2.. 方法,如 get_omitted_%d ??
我尝试在运行时创建动态函数,但遇到了一些问题。我尝试过这样的事情:
def omitted_list(self,x):
def omitted_function(self):
opk = "omitted_%d" % x
return OmittedInformationReason.objects.get(pk=self.opk).name
omitted_name = 'get_omitted_'+ str(x)
setattr(self.__class__, omitted_name , omitted_function)
omitted_name = property(omitted_name)
for x in range(1, 3):
omitted_list(x)
【问题讨论】:
-
我不知道你为什么相信代码会起作用......
-
或者你为什么认为这是一个好主意。
-
我得到 AttributeError: 'Screening' object has no attribute 'get_omitted_1' with this code
标签: python django dynamic-method