8

I'm learning by my self Python and I have a mind blowing issue, because I don't understand why is not working. I'm using PyDev and I've download version 2 of Python. I have this code:

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

and everything is working fine at this point. But if I import the Utils class and call the static method from another module...

import Utils
Utils.hello()

I get this error:

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'

I thing it can't be a big deal, but I've been searching a solution and as long I know this shlould be work.

asked Jan 2, 2014 at 10:53
4
  • 2
    Python is not php: you don't need classes to emulate namespaces. Just make hello a global function in Utils. Commented Jan 2, 2014 at 10:56
  • 2
    Python is not Java, there is absolutely no reason to have a class here, especially if all it contains is static methods. Just put hello at the top level of the file. Commented Jan 2, 2014 at 10:56
  • Thank you all. It's true, I come from Java and I use to have a static class for reusable methods. May be it's better way to do it like you say, thg435. Thanks! Commented Jan 2, 2014 at 11:24
  • 1
    No, I don't agree. I also come from Java and I want to put static method on another file, as a (good) way to separate responsibilities and also for re-usability purposes. Commented Oct 27, 2022 at 11:13

1 Answer 1

17

I believe you need to do Utils.Utils.hello()

or import like from Utils import Utils

answered Jan 2, 2014 at 10:54

2 Comments

This is why PEP8 suggests that modules should have all lowercase names. If @Hannibaal had used utils.py as the name for the module there wouldn't have been scope to confuse the module and class.
For now on my modules will be lowercase. I was confused because in java the name of the file (working with eclipse) is the class itself.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.