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

时间:2022-01-20 16:49:47

I'm trying to brush up on my python skills, and I'm dicking around with writing classes but I seem to have run into a really confusing error. Despite importing the .py file containing my class, python is insistent that the class doesn't actually exist.

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

class def:

class def:

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

    def sayHi(self):
        return self.text

main.py:

main.py:

#!/usr/bin/python
import testclass

sayinghi = greeter("hello world!")
print sayinghi.sayHi()

now as far as I can tell, I have followed all the documentation down to the 't', I even initialized arguments to None because of eval time vs creation time constraints etc which seemed to be a problem with some people, I have made sure init is the first function defined as well still to no avail, although I have a theory that the import is not working as it should.... Any help would be much appreciated.

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

2 个解决方案

#1


30  

Use the fully-qualified name:

使用完全限定名称:

sayinghi = testclass.greeter("hello world!")

There is an alternative form of import that would bring greeter into your namespace:

还有一种替代的导入形式可以为您的命名空间带来欢迎:

from testclass import greeter

#2


15  

import testclass
# change to
from testclass import greeter

or

要么

import testclass
sayinghi = greeter("hello world!")
# change to
import testclass
sayinghi = testclass.greeter("hello world!")

You imported the module/package, but you need to reference the class inside it.

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

You could also do this instead

你也可以这样做

from testclass import *

but then beware of namespace pollution

但要注意命名空间污染

#1


30  

Use the fully-qualified name:

使用完全限定名称:

sayinghi = testclass.greeter("hello world!")

There is an alternative form of import that would bring greeter into your namespace:

还有一种替代的导入形式可以为您的命名空间带来欢迎:

from testclass import greeter

#2


15  

import testclass
# change to
from testclass import greeter

or

要么

import testclass
sayinghi = greeter("hello world!")
# change to
import testclass
sayinghi = testclass.greeter("hello world!")

You imported the module/package, but you need to reference the class inside it.

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

You could also do this instead

你也可以这样做

from testclass import *

but then beware of namespace pollution

但要注意命名空间污染