使用Python程序

2024-04-20 10:43:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我对python还很陌生,我编写了以下程序:

class AddressBook:
    def __init__(self):
        self.b = {}

    def insert(self,name, phone):
        self.b[name]=phone
        print "I am confused"

    def get(self,name):
        return self.b[name]

    def has_name(self,name):
        return self.b.has_key(name)

    def list(self):
        for n,p in self.b.iteritems():
            print n,p

    def delete(self, name):
        del self.b[name]

    def orderedList(self):
        orderedkeys = self.b.keys()
        orderedkeys.sort()
        for n in orderedkeys:
            print n, self.b[n]

我现在想编译它,在终端测试它,看看它是否都能工作。 我去了目录,用

^{pr2}$

现在我想在列表中添加一些东西,打印列表的内容,删除它们(几乎是在我的程序中玩),但我不知道如何。。。在

编译之后,如何用python程序手动测试(到处玩)?在

提前谢谢。在


Tags: nameinself程序列表forreturndef
2条回答

python脚本未编译。至少不像其他语言,比如Fortran和C.From this answer

Python has a compiler! You just don't notice it because it runs automatically. You can tell it's there, though: look at the .pyc (or .pyo if you have the optimizer turned on) files that are generated for modules that you import.

Also, it does not compile to the native machine's code. Instead, it compiles to a byte code that is used by a virtual machine. The virtual machine is itself a compiled program. This is very similar to how Java works; so similar, in fact, that there is a Python variant (Jython) that compiles to the Java Virtual Machine's byte code instead! There's also IronPython, which compiles to Microsoft's CLR (used by .NET). (The normal Python byte code compiler is sometimes called CPython to disambiguate it from these alternatives.)

有两种方法可以测试:

  1. 在终端中键入python -i address.py。这将运行脚本并进入pythonshell。

  2. 输入pythonshell,然后键入from address.py import AddressBook

在这两方面,你都可以 玩你的代码。在

Python是一个interpreted language,.py文件不需要直接编译。有一个few ways to run Python code,但是为了“玩玩”,您可以简单地激活Python解释器并导入类。在

在命令提示符下:

> python

在Python中:

^{pr2}$

相关问题 更多 >