I created a class called select
that has a function s
which executes selection on the data that I initialize the select with.
For example:
select(data).s('color=red').s('tast=sweet')
This works perfectly fine.
I would like to know at the time the s
function is executed if it's the last in the line or not. How would I do that?
To clarify:
select(data).s('color=red').s('tast=sweet')
s('color=red')
is NOT the last because it's followed by .s('tast=sweet')
, while .s('tast=sweet')
IS the last, because it's not followed by anything.
Something in like this may work for you:
class Select:
def __init__(self, query=None):
self._query = query or {}
def s(self, **kwargs):
return Select({**self._query, **kwargs})
def exec(self):
print(', '.join('{}={}'.format(k, v) for k, v in self._query.items()))
This results in:
In [1]: select = Select()
In [2]: select.s(color='red').s(taste='sweet').exec()
color=red, taste=sweet
EDIT:
A little more elegant:
class Select:
def __init__(self, query=None):
self._query = query or {}
def __getattr__(self, item):
return self._arg_to_query(item)
def s(self, **kwargs):
return Select({**self._query, **kwargs})
def exec(self):
print(', '.join('{}={}'.format(k, v) for k, v in self._query.items()))
def _arg_to_query(self, arg):
def to_query(query):
return Select({**self._query, arg: query})
return to_query
This results in:
In [3]: sel = Select()
In [4]: sel.color('red').taste('sweet').exec()
color=red, taste=sweet
or combined:
In [5]: sel.color('red').taste('sweet').s(texture='smooth').exec()
color=red, taste=sweet, texture=smooth
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.