Python中的静态方法无法正常工作

Han*_*aal 4 python python-2.7

我正在通过自己的Python学习,我有一个令人兴奋的问题,因为我不明白为什么不工作.我正在使用PyDev,我已经下载了Python的第2版.我有这个代码:

class Utils:

    @staticmethod
    def hello():
        print "Hi! I'm the Utils class"

Utils.hello() #Hi! I'm the Utils class
Run Code Online (Sandbox Code Playgroud)

在这一点上,一切都很好.但是,如果我导入Utils类并从另一个模块调用静态方法...

import Utils

Utils.hello()
Run Code Online (Sandbox Code Playgroud)

我收到此错误:

Traceback (most recent call last):
  File "C:\Users\migugonz\Desktop\Docs\Per Folder\WorkSpacePy\Rosalind\src\bioinformatics\stronghold\Pruebas.py", line 40, in <module>
    Utils.hello()
AttributeError: 'module' object has no attribute 'hello'
Run Code Online (Sandbox Code Playgroud)

我认为这不是什么大不了的事,但我一直在寻找解决方案,只要我知道这应该是工作.

YOU*_*YOU 9

我相信你需要这样做 Utils.Utils.hello()

或者像进口一样 from Utils import Utils

  • 这就是为什么 PEP8 建议模块名称应全部小写。如果 @Hannibaal 使用 `utils.py` 作为模块的名称,就不会有混淆模块和类的范围。 (2认同)