JosephTLyons
JosephTLyons

Reputation: 2133

How Can Static Variables Within a Python Class Be Used in an Instance of the Class

In other languages, static variable are only accessible through the class name, and do not relate at all to an instance of that class.

I've been following the Django Polls App Tutorial. It seems that when a model is declared, the fields of that model are static variables:

class Question(models.Model):
    question_text = models.CharField(max_length=200)
    pub_date = models.DateTimeField('date published')

However, the tutorial then demonstrates how the Django shell can be used:

>>> from polls.models import Question
>>> q = Question(question_text="What's new?", pub_date=timezone.now())

This is really confusing to me, as it seems that we are constructing, q, an object that is of type Question, but that somehow is capable of holding information (question_test and pub_date) that I thought was only related to the class, not the instance (static variables).

Can someone explain to me what is going on?

How is it possible that these bits of data are able to be assigned to an instance of the class? Is this a Python or Django related thing? If so, what does q even represent? Does it represent just a row in the table?

This is pretty bizarre come from C++ where a static variable can't ever be related to an object of the class.

Upvotes: 1

Views: 224

Answers (2)

Quang Võ
Quang Võ

Reputation: 121

From what I know, models.Model has a meta class called ModelBase. So before a Question class create, the meta class will be triggered and attach attributes to a class. So when the class Question is created, it's already have that attribute and value. Question represent a table Question in your database

Upvotes: 2

Lord Elrond
Lord Elrond

Reputation: 16062

The Question class represents an entire database table, and each attribute (model field) of the Question class represents a single column in that table.

When you initialize a model, for example:

question1 = Question(question_text='foo', pub_date='2019-12-12')

You create an instance of that model, which represents a single row in your Question table, however question1 won't hit the database until you call it's save() method:

question1.save()

Upvotes: 1

Related Questions