Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Instance variables of class-based-views persistent?

I've just started using class-based views in django. But there's an issue that is confusing for me. I ran the following code snippet with django 1.4.1 with multithreaded development server.

class TestView(TemplateView):
    template_name = 'test.html'
    count = 0
    mylist = [1, ]

    def get(self, request, *args, **kwargs):
        self.count += 1
        self.mylist.append(self.mylist[-1] +1)
        context = self.get_context_data(**kwargs)
        return self.render_to_response(context)

    def get_context_data(self, **kwargs):
        context = super(TestView, self).get_context_data(**kwargs)
        context['count'] = self.count
        context['mylist'] = self.mylist
        return context

The template just outputs the context variables count and mylist. When this view is called e.g. up to 5 times the output will look like this:

count: 1
mylist: [1, 2, 3, 4, 5, ]

And now I'm confused. The django docs says, that each request has its own individual class instance.

So how it is possible to extend mylist over several requests? Why the count variable was not incremented?

like image 510
user1603806 Avatar asked Aug 16 '12 19:08

user1603806


People also ask

Are instance variables unique to a class?

Class variables are shared across all objects while instance variables are for data unique to each instance.

Are instance variables always public?

Default Values of Instance Variables in Java: The first property is that instance variables are by default public. This means that any class in your application can access them. You can, however, make an instance variable private, which would restrict access to it only to the class in which it is declared.

Are instance variables and class variables same?

Instance Variable: It is basically a class variable without a static modifier and is usually shared by all class instances. Across different objects, these variables can have different values.

Which is correct about an instance variable?

Instance variables have a default value based on the type. For any non-primitive, including String, that type is a reference to null. Option B is correct.


1 Answers

If you need something available over several requests, you need to add it to the session. An ivar is not the place for that. For thread-safety, the as_view method returns a brand new instance of the class each time, which is not effected by anything else that happens on any other instances of the same class. This is by design and you'd have numerous problems if it wasn't the case.

like image 79
Chris Pratt Avatar answered Sep 28 '22 02:09

Chris Pratt