尽管导入了类,但未定义类

Dam*_*ayn 22 python module class

我正在努力提高我的python技能,而且我正在努力编写类,但我似乎遇到了一个非常令人困惑的错误.尽管导入了包含我的类的.py文件,但python坚持认为该类实际上并不存在.

class def:

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

    def sayHi(self):
        return self.text
Run Code Online (Sandbox Code Playgroud)

main.py:

#!/usr/bin/python
import testclass

sayinghi = greeter("hello world!")
print sayinghi.sayHi()
Run Code Online (Sandbox Code Playgroud)

现在据我所知,我已经将所有文档都记录到了't',我甚至将参数初始化为None,因为eval时间与创建时间限制等等似乎是某些人的问题,我已经确定了init是第一个定义的函数,但仍无济于事,尽管我有一个理论认为导入不能正常工作......任何帮助都会非常感激.

NPE*_*NPE 32

使用完全限定名称:

sayinghi = testclass.greeter("hello world!")
Run Code Online (Sandbox Code Playgroud)

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

from testclass import greeter
Run Code Online (Sandbox Code Playgroud)


Chr*_*tts 17

import testclass
# change to
from testclass import greeter
Run Code Online (Sandbox Code Playgroud)

要么

import testclass
sayinghi = greeter("hello world!")
# change to
import testclass
sayinghi = testclass.greeter("hello world!")
Run Code Online (Sandbox Code Playgroud)

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

你也可以这样做

from testclass import *
Run Code Online (Sandbox Code Playgroud)

但要注意命名空间污染