Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python class static methods

Tags:

python

static

I want to create a kind of utility class which contains only static methods which are callable by the name class prefix. Looks like I'm doing something wrong :)

Here is my small class:

class FileUtility():

    @staticmethod
    def GetFileSize(self, fullName):
        fileSize = os.path.getsize(fullName)
        return fileSize

    @staticmethod
    def GetFilePath(self, fullName):
        filePath = os.path.abspath(fullName)
        return filePath

Now my "main" method:

from FileUtility import *
def main():
        path = 'C:\config_file_list.txt'
        dir = FileUtility.GetFilePath(path)
        print dir

and I got an error: unbound method GetFilePath() must be called with FileUtility instance as first argument (got str instance instead).

A have a few questions here:

  1. What am I doing wrong? Should not the static method be callable by classname?
  2. Do I really need a utility class, or are there other ways to achieve the same in Python?
  3. If I try to change the code in main I'm getting: TypeError: GetFilePath() takes exactly 1 argument (2 given)

The new main:

from FileUtility import *
def main():
    objFile = FileUtility()
    path = 'H:\config_file_list.txt'
    dir = objFile.GetFilePath(path)
    print dir
like image 744
ilyaw77 Avatar asked Oct 04 '12 20:10

ilyaw77


People also ask

What are static methods in Python class?

What is a static method? 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.

How do you call a static method from a class in Python?

The static method works similarly to a function in a Python script, but it is located within the class body. A static method can be called from either a class or object reference. We can call it Utils if foo() is a static function in Class Utils. Utils.

When should a method be static Python?

2. Having a single implementation. Static methods are used when we don't want subclasses of a class change/override a specific implementation of a method.

What is the difference between static method and class method in Python?

The static method does not take any specific parameter. Class method can access and modify the class state. Static Method cannot access or modify the class state. The class method takes the class as parameter to know about the state of that class.


7 Answers

You're getting the error because you're taking a self argument in each of those functions. They're static, you don't need it.

However, the 'pythonic' way of doing this is not to have a class full of static methods, but to just make them free functions in a module.

#fileutility.py:

def get_file_size(fullName):
    fileSize = os.path.getsize(fullName)
    return fileSize


def get_file_path(fullName):
    filePath = os.path.abspath(fullName)
    return filePath

Now, in your other python files (assuming fileutility.py is in the same directory or on the PYTHONPATH)

import fileutility

fileutility.get_file_size("myfile.txt")
fileutility.get_file_path("that.txt")

It doesn't mention static methods specifically, but if you're coming from a different language, PEP 8, the python style guide is a good read and introduction to how python programmers think.

like image 54
Collin Avatar answered Sep 30 '22 09:09

Collin


You really shouldn't be creating static methods in Python. What you should be doing is putting them at the global function level, and then accessing the module they're in when you call them.

foo.py:

def bar():
  return 42

baz.py:

import foo
print foo.bar()
like image 23
Ignacio Vazquez-Abrams Avatar answered Sep 27 '22 09:09

Ignacio Vazquez-Abrams


Static methods don't get the object passed in as the first parameter (no object)

remove the self parameter and the calls should work. The import problem is relevant too. And the static comment relevant too.

like image 36
Hedlok Avatar answered Sep 29 '22 09:09

Hedlok


In python, java-like (or whatever) static methods are not widely used as they don't really have a purpose.

Instead, you should simply define your "methods" as functions in a module:

#module1.py
def fun1():
    return do_stuff()
def fun2(arg):
    return do_stuff_with_arg(arg)

#main.py
import module1
if __name__ == '__main__':
    a = module1.fun()
    print module1.fun2(a)
like image 25
Thomas Orozco Avatar answered Sep 30 '22 09:09

Thomas Orozco


Just remove self in methods definition. Your intention is to use as static. Self is to work with instance of that class.

like image 29
Saleem Khan Avatar answered Sep 27 '22 09:09

Saleem Khan


Just remove the self in the function definition. Since your using the static functions so you need not pass self as an argument for the functions. So your class and function should be like this:

class FileUtility():

    @staticmethod
    def GetFileSize(fullName):
        fileSize = os.path.getsize(fullName)
        return fileSize

    @staticmethod
    def GetFilePath(fullName):
        filePath = os.path.abspath(fullName)
        return filePath
like image 20
Shreyas sreenivas Avatar answered Oct 01 '22 09:10

Shreyas sreenivas


If you want to use your functions defined in the class, you have just to create an instance of your class and apply the function.

So the result is :

dir = FileUtility().GetFilePath(path)

Just add () after your class name.

@staticmethod is not needed as you are using standard function, not static. But in your case the result is the same.

like image 27
Pollux31 Avatar answered Oct 01 '22 09:10

Pollux31