I am trying to make self.id show exact value. I made it but I'm wondering how can I improve it?
self.id = 36
def OnClickNextPage(self):
if self.id == 36:
self.id = 37
elif self.id == 37:
self.id = 1020
elif self.id == 1020:
self.id = 2020
elif self.id == 2020:
self.id = 3019
elif self.id == 3019:
self.id = 5015
elif self.id == 5015:
self.id = 7019
else:
return
def OnClickPrevPage(self):
if self.id == 36:
return
elif self.id == 37:
self.id = 36
elif self.id == 1020:
self.id = 37
elif self.id == 2020:
self.id = 1020
elif self.id == 3019:
self.id = 2020
elif self.id == 5015:
self.id = 3019
elif self.id == 7019:
self.id = 5015
else:
return
I expect to get the exact value, but I'm not really sure how to make it smarter.
If you're just looking to shorten it, you can use lists for self.id values and the values you want to change it to. For the first function:
def OnClickNextPage(self):
possible_ids = [36, 37, 1020, 2020, 3019, 5015]
change_id = [37, 1020, 2020, 3019, 5015, 7019]
if self.id in possible_ids:
self.id = change_id[possible_ids.index(self.id)]
return self
else:
return self
Make sure you return self so that it updates self.id for the object.
You can make the IDs a list and keep track of which page (index) you're on instead. Make id a property so that you can easily calculate it based on the current index as needed:
class Pages:
def __init__(self, ids):
self.ids = ids
self.index = 0
@property
def id(self):
return self.ids[self.index]
def OnClickNextPage(self):
self.index += 1
def OnClickPrevPage(self):
self.index -= 1
pages = Pages([36, 37, 1020, 2020, 3019, 5015])
print(pages.id)
pages.OnClickNextPage()
print(pages.id)
pages.OnClickNextPage()
print(pages.id)
pages.OnClickPrevPage()
print(pages.id)
This outputs:
36
37
1020
37
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