首先,我不喜欢网络编程。我碰到了django,并阅读了一些有关模型的信息。以下代码(djangoproject.com)吸引了我:
class Person(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __str__(self): # Note use of django.utils.encoding.smart_str() here because # first_name and last_name will be unicode strings. return smart_str('%s %s' % (self.first_name, self.last_name))
据我对python的理解,first_name和last_name是类变量,对吗?它在代码中如何使用(因为我猜设置Person.first_name或Person.last_name将影响所有Person实例)?为什么使用这种方式?
是的,first_name和last_name是类变量。它们定义将在数据库表中创建的字段。有一个Person表,该表具有first_name和last_name列,因此此时将它们置于类级别是有意义的。
有关模型的更多信息,请参见:http : //docs.djangoproject.com/en/dev/topics/db/models/
当涉及到在代码中访问Person的实例时,通常是通过Django的ORM来执行此操作,此时,它们实际上起着实例变量的作用。
有关模型实例的更多信息,请参见:http : //docs.djangoproject.com/en/dev/ref/models/instances/?from=olddocs