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.
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 = []
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With