The goal is to reduce the following code to as few lines (and as few characters) of code as possible. It doesn't need to be 'readable' or even 'pythonic', just sh开发者_JAVA技巧ort and sweet. this ones more for fun.
self.BlueEgg = PhotoImage(file="assets/blueegg.gif")
self.PolkaEgg = PhotoImage(file="assets/polkaegg.gif")
self.RedEgg = PhotoImage(file="assets/redegg.gif")
self.StripeEgg = PhotoImage(file="assets/sripeegg.gif")
self.YellowEgg = PhotoImage(file="assets/yellowegg.gif")
self.PurpleEgg = PhotoImage(file="assets/purpleegg.gif")
self.PinkEgg = PhotoImage(file="assets/pinkegg.gif")
self.OrangeEgg = PhotoImage(file="assets/orangeegg.gif")
self.CrazyEgg = PhotoImage(file="assets/crazyegg.gif")
self.PlainEgg = PhotoImage(file="assets/plainegg.gif")
It does vaugly apply to my program, but i more-so just wanted to see what you guys could come up with! happy easter everyone!
The only thing that changes is the type of egg, which changes the attribute on self and the filename. So...
types = ('Blue', 'Polka', 'Red', 'Stripe', 'Yellow', 'Purple', 'Pink', 'Orange', 'Crazy', 'Plain')
for t in types:
setattr(self, '%sEgg' % t, PhotoImage(file='assets/%segg.gif' % t.lower()))
Store atributes and filenames in tuples in a list:
mylistoftuples = [('BlueEgg', "assets/blueegg.gif"), .......]
then, assign in a loop:
for attr, filename in mylistoftuples:
setattr(self, attr, PhotoImage(file=filename))
Note you have two other possibilities to massage the code:
1) the directory is always the same, so you dont need to hardcode the assets/xxxx.gif thing for each item in the list. You can build it inside the for-loop.
2) filenames are equal to the attribute in lowercase. So if you store only the attribute (p.e. BluEgg) in the list instead of a tuple, you can derive the filepath from it:
mylist = ['BlueEgg', .......]
for attr in mylist:
filename = os.path.join('assets', '%s.gif' % attr.lower())
setattr(self, attr, PhotoImage(file=filename))
精彩评论