問題描述
django 網(wǎng)站上的教程顯示了模型的以下代碼:
The tutorial on the django website shows this code for the models:
from django.db import models
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
現(xiàn)在,這些屬性中的每一個(gè)都是類屬性,對吧?因此,該類的所有實(shí)例都應(yīng)共享相同的屬性.稍后,他們展示了這段代碼:
Now, each of those attribute, is a class attribute, right? So, the same attribute should be shared by all instances of the class. A bit later, they present this code:
class Poll(models.Model):
# ...
def __unicode__(self):
return self.question
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
它們是如何從類屬性轉(zhuǎn)變?yōu)閷?shí)例屬性的?我是不是把類屬性弄錯(cuò)了?
How did they turn from class attributes into instance attributes? Did I get class attributes wrong?
推薦答案
看看django/db/models.py下的Model
類.在那里,類屬性通過類似的方式轉(zhuǎn)換為實(shí)例屬性
Have a look at the Model
class under django/db/models.py. There the class attributes are turned to instance attributes via something like
setattr(self, field.attname, val)
人們可能會推薦整個(gè)文件(ModelBase
和 Model
類)作為元類的優(yōu)秀實(shí)踐示例.
One might recommend the whole file (ModelBase
and Model
class) as an excellent hands-on example on metaclasses.
這篇關(guān)于Django 模型與Python 類屬性的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!