how.wtf

Static methods in Python

· Thomas Taylor

Static methods are similar to instance methods (class-level methods), except static methods behave like regular functions bound to a class namespace. Unlike instance methods, static methods do not have access to cls or self.

Creating static methods

A class named StringUtil contains a is_empty method for determining if a string is empty.

1class StringUtil:
2    @staticmethod
3    def is_empty(s):
4        return not s.strip()
5
6print(StringUtil.is_empty("test")) # False
7print(StringUtil.is_empty(" ")) # True

When to use static methods

Static methods are advantageous for:

#python  

Reply to this post by email ↪