我在网上看到过人们使用的例子__getattr__
使用 Django 模型,但每当我尝试时都会出错。 (姜戈1.2.3)
我使用的时候没有任何问题__getattr__
在普通物体上。例如:
class Post(object):
def __getattr__(self, name):
return 42
工作得很好...
>>> from blog.models import Post
>>> p = Post()
>>> p.random
42
现在,当我尝试使用 Django 模型时:
from django.db import models
class Post(models.Model):
def __getattr__(self, name):
return 42
并在解释器上测试它:
>>> from blog.models import Post
>>> p = Post()
ERROR: An unexpected error occurred while tokenizing input The
以下回溯可能已损坏
或无效 错误消息为:('EOF
在多行语句中', (6, 0))
-------------------------------------------------- -------------------------- 类型错误
回溯(最近一次调用最后一次)
/用户/乔什/项目/
在 ()
/Users/josh/project/lib/python2.6/site-packages/django/db/models/base.pyc
在init(自我,*args,**kwargs)
第338章
第339章
该函数的参数" %
kwargs.keys()[0])
--> 340 信号.post_init.send(sender=self.class,
实例=自身)
第341章
342 防御repr(self):
/Users/josh/project/lib/python2.6/site-packages/django/dispatch/dispatcher.pyc
在发送(自我,发件人,**命名)
160
161 self._live_receivers(_make_id(sender))中的接收者:
--> 162 响应 = 接收者(信号=自身,发送者=发送者,
**命名)
163 响应.append((接收者,响应))
164 回复
/Users/josh/project/python2.6/site-packages/photologue/models.pyc
在add_methods(发件人,实例,
信号,*args,**kwargs)
第728章
第729章
--> 730 实例.add_accessor_methods()
第731章
第732章
post_init 信号
类型错误:“int”对象不是
可调用的
有人可以解释发生了什么事吗?
编辑:我在示例中可能过于抽象,这里有一些代码更接近我在网站上实际使用的代码:
class Post(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField()
date_published = models.DateTimeField()
content = RichTextField('Content', blank=True, null=True)
# Etc...
Class CuratedPost(models.Model):
post = models.ForeignKey('Post')
position = models.PositiveSmallIntegerField()
def __getattr__(self, name):
''' If the user tries to access a property of the CuratedPost, return the property of the Post instead... '''
return self.post.name
# Etc...
While I could为 Post 类的每个属性创建一个属性,这会导致大量代码重复。此外,这意味着每当我添加或编辑 Post 类的属性时,我都必须记住对 CuratedPost 类进行相同的更改,这似乎是代码腐烂的秘诀。