[Tutor] Shorten Code.

Mic o0MB0o at hotmail.se
Fri Nov 18 09:16:46 CET 2011

From: Wayne Werner 
Sent: Thursday, November 17, 2011 8:30 PM
To: Mic 
Cc: tutor at python.org 
Subject: Re: [Tutor] Clock in tkinter?

  Say that I have a class and I want to make 100 objects. 
  Then it could look like this:
  class Chairs(object):
  <snip code> 
  #Create the objects

  How do I shorten this? I have thought of using a for sling. I have looked in my programming
  book and on the internet, but I don’t know how to make this shorter. The arguements (“10”, “20”)
  should be the same for every object, which should make it easier than if they were different each time?

If you ever write a line of code more than once, it's a good sign that you have what's called a code smell. This example is very smelly code ;)

What you should do instead is have a collection of chairs:

chairs = []
for _ in range(100): # the underscore `_` indicates that you don't care about the value

Yes, I got that right now. But now that you talked about shortening code, I have a general question.
What if I don’t write the same line of code more than once, but I write similiar lines more than once. Is that okay? 

For example:


I know that I can make this shorter, with a for sling for example, but the problem is that 
I need to use these variables later in my program, and I don’t know how do to then, to be able
to use them later on, in a function for example. Do you have any general tips on how to make
your code shorter?

I also hope I have learnt to post better now.


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111118/5a391cd9/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: wlEmoticon-smile[1].png
Type: image/png
Size: 1041 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/tutor/attachments/20111118/5a391cd9/attachment.png>

More information about the Tutor mailing list