Classes and the command line

Ben Finney ben+python at benfinney.id.au
Mon Oct 27 04:06:11 CET 2014


Seymore4Head <Seymore4Head at Hotmail.invalid> writes:

> I am trying to learn classes.
> I am currently using Python 2.7 at the command line.

(I think you mean “the interactive Python interpreter”, or just “the
Python shell”.)

Since you are learning Python, I will strongly recommend you ignore
Python 2 unless it becomes unavoidable.

Instead, learn Python 3 primarily; it is much better because it omits a
bunch of legacy behaviour you don't need.

> If you try to type commands at the [interactive shell] and make the
> slightest mistake you have to start over.

Right. There is line-by-line history, and editing enabled with the
“readline” plug-in. (This is an advantage of using a programmer-friendly
operating system, which MS Windows sadly is not.)

> I was trying to copy and paste these instructions into the
> [interactive Python shell].
>
> http://en.wikibooks.org/wiki/Python_Programming/Classes
> >>> class Foo:
> ...     def setx(self, x):
> ...         self.x = x
> ...     def bar(self):
> ...         print self.x
>
> There is really no way to do that without pasting line by line is
> there and adding deleting spaces?  And if you use spaces and tabs,
> they are not the same.

Right on all counts.

The interactive Python shell is good for very quickly experimenting and
demonstrating how Python actually behaves, statement by statement. But
as you point out, it is not a good choice for anything more complex. It
is a good learning and debugging tool.

When you start to write larger units of code, like a class or a
function, you can trade immediacy for flexibility: write your code into
a text editor, save it to a file ‘foo.py’, then run that code at a
separate OS command prompt by invoking ‘python foo.py’ in the terminal.

That way, you can continue to adjust and tweak the code as you learn how
your changes affect the code. You do need to keep invoking the actions
separately – edit the file, save the file, run the file with Python –
but this is what's needed when you want to run a program more than once
anyway, so it's a good step to take.

Find a good, *general-purpose* programmer's editor. Preferably licensed
under free software terms, with a strong community supporting it, and
available on all major platforms for when you switch to a decent
programmer-friendly operating system.

-- 
 \        “When you go in for a job interview, I think a good thing to |
  `\                  ask is if they ever press charges.” —Jack Handey |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list