79330

What's the difference to use @staticmethod and global function in Python?

Question:

I have read

<ul><li><a href="https://stackoverflow.com/questions/136097/what-is-the-difference-between-staticmethod-and-classmethod-in-python" rel="nofollow">What is the difference between @staticmethod and @classmethod in Python?</a> </li> <li><a href="https://stackoverflow.com/questions/12179271/python-classmethod-and-staticmethod-for-beginner" rel="nofollow">Python @classmethod and @staticmethod for beginner?</a></li> </ul>

As staticmethod can't access the instance of that class, I don't know what's the difference betweent it and global function?

And when should use staticmethod? Can give a good example?

Answer1:

Like global function, static method cannot access the instance of the containing class. But it conceptually belongs to the containing class. The other benefit is it can avoid name confliction.

When the function is designed to serve for some given class, it's advisable to make it as a static method of that class. This is called <a href="http://en.wikipedia.org/wiki/Cohesion_%28computer_science%29" rel="nofollow">cohesion</a>. Besides, if this function is not used outside, you can add underscore before it to mark it as "private", this is called <a href="http://en.wikipedia.org/wiki/Information_hiding" rel="nofollow">information hiding</a>(despite Python doesn't really support private methods). As a rule of thumb, exposing as little interfaces as possible will make code more clean and less subject to change.

Even if that function is supposed to serve as a shared utility for many classes that are across multiple modules, making it a global function is still not the first choice. Consider to make it as some utility class's static method, or make it a global function in some specialized module. One reason for this is collecting similar-purposed functions into a common class or module is good for another level's abstraction/modularization(for small projects, some people may argue that this is overengineering). The other reason is this may reduce namespace pollution.

Answer2:

A static method is contained in a class (adding a namespace as pointed out by @MartijnPieters). A global function is not.

Answer3:

IMO it is more of a design question, rather than a technical one. If you feel that the logic belongs to a class (not the instance) add it as a staticmethod, if it's unrelated implement it as a global function.

For example:

class Image(object): @staticmethod def to_grayscale(pixel): # ...

IMO is better than

def to_grayscale(pixel): #... class Image(object): # ...

Recommend

  • How do I loop through date values stored as numbers within For Loop container?
  • How to generate a random number in the constructor of a class in C#
  • How to disable warning in React Native ?
  • MIPS assembly - Label value modification
  • codechef :wrong answer error in smallfactorial
  • Initial commit of major projects to mercurial
  • Mapping multiple domain names to different resources in a Rails app
  • Filter log files(_success and _log) in FileSystem.liststatus
  • Dynamically Load Extjs Modular application
  • karma-browserify throws error when trying to load modules shimmed with browserify-shim
  • Jquery javascript: have a filtering list(works), need help keeping all LI's visible when there&
  • How to hide the cursor in windows when dragging and dropping (possibly in python, or another languag
  • rails 5 carrierwave no route matches for image
  • Calling a second level base class constructor
  • How to use the File System Events API in Swift?
  • Column Nullability/Optionality: NULL vs NOT NULL
  • What's the benefit of the trailing apostrophe in character literals
  • AOT and JIT with build-optimizer
  • How to show underscore (shortcut) without holding Alt?
  • When interface inheritance in Java is useful?
  • How many Vertica Databases can run on a Host in the same time?
  • Mercurial: Identify file name after rename
  • EF 4.1 DBContext AutoDetectChangesEnabled
  • How do you create a Fuseki SPARQL server using the Apache Jena Java API?
  • What is the use of a session store?
  • File extension of zlib zipped html page?
  • Android full screen on only one activity?
  • DirectX11 ClearRenderTargetViewback with transparent buffer?
  • How to apply VCL Styles to DLL-based forms in Inno Setup?
  • Javascript + PHP Encryption with pidCrypt
  • Why is the timeout on a windows udp receive socket always 500ms longer than set by SO_RCVTIMEO?
  • Web-crawler for facebook in python
  • Unit Testing MVC Web Application in Visual Studio and Problem with QTAgent
  • Angular 2 constructor injection vs direct access
  • Getting Messege Twice Using IMvxMessenger
  • Java static initializers and reflection
  • Android Google Maps API OnLocationChanged only called once
  • How can i traverse a binary tree from right to left in java?
  • UserPrincipal.Current returns apppool on IIS
  • How can I use threading to 'tick' a timer to be accessed by other threads?