0

我写了以下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 中

4

3 回答 3

1

然后将您的文件 my.py 放入 PYTHONPATH

from my import ArithmeticSequence
s=ArithmeticSequence(1,2)
于 2013-06-05T18:38:41.080 回答
0

好吧,您要么必须使用它作为程序运行它

if __name__ == 'main':
    # Your code goes here. This will run when called from command line.

或者,如果您在 python 解释器中,则必须使用以下命令导入“my”:

>>> import my
于 2013-06-05T18:30:59.960 回答
0

您要运行的命令是:

python -i my.py

这将解析 my.py 并定义 name ArithmeticSequence,然后将您放入 Python shell 中,您可以在其中交互式地使用您的对象:

>>> s=ArithmeticSequence(1,2)
>>> 
于 2013-06-05T19:31:27.273 回答