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.
Unlike instance methods, static methods aren't bound to an object. In other words, static methods cannot access and modify an object state. In addition, Python doesn't implicitly pass the cls parameter (or the self parameter) to static methods. Therefore, static methods cannot access and modify the class's state.
To declare a static method, use this idiom: class C: @staticmethod def f(arg1, arg2, ...): ... The @staticmethod form is a function decorator – see the description of function definitions in Function definitions for details. It can be called either on the class (such as C.f() ) or on an instance (such as C().
Static methods in Python are extremely similar to python class level methods, the difference being that a static method is bound to a class rather than the objects for that class. This means that a static method can be called without an object for that class.
Static methods are a special case of methods. Sometimes, you'll write code that belongs to a class, but that doesn't use the object itself at all. It is a utility method and doesn't need an object ( self parameter) to complete its operation.
I believe you need to do Utils.Utils.hello()
or import like from Utils import Utils
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With