Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static method in Python not working

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.

like image 348
Hannibaal Avatar asked Jan 02 '14 10:01

Hannibaal


People also ask

Why not use static methods Python?

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.

How do you declare a static method in Python?

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().

Is it possible to have static methods in Python?

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.

Do static methods need self?

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.


1 Answers

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

or import like from Utils import Utils

like image 171
YOU Avatar answered Nov 15 '22 03:11

YOU