我写了以下python程序
#! /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
我做的时候程序是my.py
chmod +x my.py
python my.py
在这一步之后我回到了bash shell 我打开一个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
如何为我的程序提供输入并运行它,因为它已保存在vi
中答案 0 :(得分:1)
将文件my.py放在PYTHONPATH中 然后
from my import ArithmeticSequence
s=ArithmeticSequence(1,2)
答案 1 :(得分:0)
你要么必须使用
将其作为程序运行if __name__ == 'main':
# Your code goes here. This will run when called from command line.
或者如果您在python解释器中,则必须使用以下内容导入“my”:
>>> import my
答案 2 :(得分:0)
您要运行的命令是:
python -i my.py
这将解析my.py并定义名称ArithmeticSequence
,然后将您放到Python shell中,您可以在其中以交互方式使用对象:
>>> s=ArithmeticSequence(1,2)
>>>