Django models & Python class attributes

后端 未结 4 1713
再見小時候
再見小時候 2021-01-12 06:09

The tutorial on the django website shows this code for the models:

from django.db import models

class Poll(models.Model):
    question = models.CharField(ma         


        
相关标签:
4条回答
  • 2021-01-12 06:32

    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)
    

    One might recommend the whole file (ModelBase and Model class) as an excellent hands-on example on metaclasses.

    0 讨论(0)
  • 2021-01-12 06:32

    A class instance has a namespace implemented as a dictionary which is the first place in which attribute references are searched.

    http://docs.python.org/reference/datamodel.html

    0 讨论(0)
  • 2021-01-12 06:36

    In Python, a class attribute is always also an instance attribute:

    class C(object):
        a = 1
        def show_a(self):
            print self.a # <- works
    

    But in django it is further complicated by the fact that Model classes have special metaclasses, so be careful to your assumptions!

    0 讨论(0)
  • 2021-01-12 06:45

    It's done with metaclasses - very clever stuff. I'd recommend Marty Alchin's excellent book Pro Django if you want to learn more.

    0 讨论(0)
提交回复
热议问题