35

我似乎遇到了一个非常令人困惑的错误。尽管导入了包含我的类的 .py 文件,Python 坚持认为该类实际上并不存在。

testmodule.py 中的类定义:

class Greeter:
    def __init__(self, arg1=None):
        self.text = arg1

    def say_hi(self):
        return self.text

主要.py:

#!/usr/bin/python
import testmodule

sayinghi = Greeter("hello world!")
print(sayinghi.say_hi())

我有一个理论,即导入没有按应有的方式工作。我该如何正确地做到这一点?

4

2 回答 2

39

使用完全限定名称:

sayinghi = testmodule.Greeter("hello world!")

有一种替代形式import可以带入Greeter您的命名空间:

from testmodule import Greeter
于 2012-05-23T14:48:49.577 回答
24
import testmodule
# change to
from testmodule import Greeter

或者

import testmodule
sayinghi = Greeter("hello world!")
# change to
import testmodule
sayinghi = testmodule.Greeter("hello world!")

您导入了模块/包,但您需要引用其中的类。

你也可以这样做

from testmodule import *

但要小心命名空间污染

于 2012-05-23T14:52:05.170 回答