4

I have a python object which collects some request data so I can create the model queries based on the filters and sorters I receive via GET method. (sort=id&order=DESC...)

class Search( object ):
 sorters = []
 filters = []

If the request has filters and sorters the class properties get filled with the right params. This works well and the queries are built ok. The problem is when I trigger a second request, sorters and filters retain the values from the previous request so the Search object is not new but persistent.

Any idea why it behaves like this? Btw I'm new to python, PHP (my area) will just instantiate a new object per request.

Anconia
4,0586 gold badges40 silver badges66 bronze badges
asked Jun 21, 2011 at 17:44
1
  • This is hard to answer without the specifics of the framework you are using (i.e. how a Search object is instantiated, etc), but from what I can see, these attributes are class attributes, not object ones. By definition, they are shared between instantiated objects. Commented Jun 21, 2011 at 17:50

2 Answers 2

7

Because you are creating class variables rather than member variables this way. Class variables are shared among every instance (they belong to the class, not an instance); they are similar to static member variables in other languages.

To create member variables, you need to initialise them in the constructor, like this:

class Search(object):
 def __init__(self):
 self.sorters = []
 self.filters = []
answered Jun 21, 2011 at 17:50

2 Comments

oh. I was doing it the PHP way it seems. Thanks for the answer.
Holy guacamole! I had the exact same problem (on a slightly higher level) and your answer helped me fix the issue. Thanks a million. Would give you 1000 upvotes but sadly I can't.
1

If you want sorters and filters as instance members of Search, you'll need to define them as such.

class Search( object ):
 def __init__(self, sorters=None, filters=None):
 self.sorters = [] if sorters == None else sorters
 self.filters = [] if filters == None else filters

This will allow you to instantiate either by providing the sorters and filters at initialization, or by assigning them to the object later on. Or both.

answered Jun 21, 2011 at 17:52

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.