Reputation: 5361
I wrote following python program
#! /usr/bin/python
def checkIndex(key):
if not isinstance(key, (int, long)): raise TypeError
if key<0: raise IndexError
class ArithmeticSequence:
def __init__(self, start=0, step=1):
self.start = start # Store the start value
self.step = step # Store the step value
self.changed = {} # No items have been modified
def __getitem__(self, key):
checkIndex(key)
try: return self.changed[key]
except KeyError:
return self.start + key*self.step
def __setitem__(self, key, value):
checkIndex(key)
self.changed[key] = value
the program is my.py when I do
chmod +x my.py
python my.py
I am back to bash shell here after this step I open a python shell
user@ubuntu:~/python/$ python
Python 2.7.3 (default, Aug 1 2012, 05:14:39)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s=ArithmeticSequence(1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'ArithmeticSequence' is not defined
How do I give input to my program and run it because it was saved in vi
Upvotes: 0
Views: 156
Reputation: 10955
The command that you want to run is:
python -i my.py
That will parse my.py and define the name ArithmeticSequence
, and drop you into the Python shell where you can use your objects interactively:
>>> s=ArithmeticSequence(1,2)
>>>
Upvotes: 0
Reputation: 71
Put your file my.py in PYTHONPATH then
from my import ArithmeticSequence
s=ArithmeticSequence(1,2)
Upvotes: 1
Reputation: 747
Well you either have to run this as a program using
if __name__ == 'main':
# Your code goes here. This will run when called from command line.
or if you are in the python interpreter you have to import "my" with:
>>> import my
Upvotes: 0